4

Possible Duplicate:
How do I determine if an array is initialized in VB6?

I declare an array initially as empty:

Dim ArrayVar() as Variant


'May add some data, may not
if something then 
    Redim Preserve ArrayVar(ubound(ArrayVar,1)+1)
    ArrayVar(ubound(ArrayVar,1)) = "something"
end if


'Always check size of array
if ubound(ArrayVar,1) > x

the problem is sometimes when I reach checking the size, nothing has been added- the array is empty and I get a run-time error. I did try declaring the array with Dim ArrayVar(0) as Variant but then the redim statement wouldnt compile.

Whats the best way to do this?

Community
  • 1
  • 1
intrigued_66
  • 16,082
  • 51
  • 118
  • 189

1 Answers1

2

You can use the IsEmpty() function.

Please try the following code:

Dim ArrayVar() As Variant

Sub x()
If IsEmpty(arrvar) Then
    ReDim ArrayVar(0)
Else
    ReDim Preserve ArrayVar(UBound(ArrayVar, 1) + 1)
    ArrayVar(UBound(ArrayVar, 1)) = "something"
End If

MsgBox UBound(ArrayVar, 1)
End Sub
Kovags
  • 540
  • 3
  • 16
  • 2
    `IsEmpty` cannot be used to determine if an array is empty (it will always return `False`). This code works only because the array variable is `ArrayVar`, but the code checks `arrvar` for emptiness. If you fix it and correctly call `IsEmpty(ArrayVar)`, you will have runtime error 9 on trying to get `UBound(ArrayVar, 1)` of the empty array. – GSerg Mar 13 '19 at 14:00