We help IT Professionals succeed at work.

Dynamic Arrays

hozempa asked
Medium Priority
Last Modified: 2010-08-05
Simple question.  When I initially declare a dynamic array (for example, Dim Array() as User-Defined Type) will it's length automatically be set to 0, assuming Option Base 0?  If so, how do I check and confirm that the array is empty?
Thanks in advance, John
Watch Question

Unlock this solution and get a sample of our free trial.
(No credit card required)
if first field is numeric

if Array(0).UDTField1=0 then
  msgbox "is empty"
  msgbox "is not empty"


Your answer has two problems.
1. The array may not be initialized.  If this is the case, you will get a subscript out of range error.
2. The value of Array(0).UDTField1 just may be 0 (or "") as a valid entry.

The only way is to try to read the array and if the err,number = 9 then it is un-initialized.

Here is an example which will show "Is empty" the first time and "Is not empty" the second time.

  Dim MyArray() As tUDT
  Dim nDummy As Integer
  On Error Resume Next
  nDummy = MyArray(LBound(MyArray)).UDTField1
  If Err.Number = 9 Then
    MsgBox "Is empty"
    MsgBox "Is not empty"
  End If
  ReDim MyArray(1)
  nDummy = MyArray(LBound(MyArray)).UDTField1
  If Err.Number = 9 Then
    MsgBox "is empty"
    MsgBox "is not empty"
  End If

To (slightly) improve on my above example, declare nDummy as a variant.


Thank you for the information.  Still, I am curious to know if the statement 'Dim Array() As User-Defined Type' creates an element of 1, Array(0).  I assume that it doesn't, can anyone verify this?
ClifABB, you're right

But after declaring the array, if
Redim Array(0) as UDT
as been made, the array has been initialized and I don't
think that all fields in the UDT should be empty at a time,
only if hozempa wants so.

No, the statement Dim Array() as Anything doesn't create any elements.  This is termed 'Uninitialized'.  You can test this with the code:
Dim MyArray As tUserDefinedType
Debug.Print MyArray(0).Field1

Which will give you an array out of bounds error.
Instead of declaring like this:
Dim MyArray() As tUserDefinedType

You could declare:
ReDim MyArray(0) As tUserDefinedType
and the array will be at once declared and initialized.

Hope this helps


Thank you fguerreiro_inix and clifABB, both of you deserve the points. I'll address a question to you clifABB and you can pick up the 5 points.  Thanks again.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.