moony
moony

Reputation: 434

vb6 how to resize dynamic arrays

In vb6 I have an dynamic array defined like this because I don't know how many values to be added while running the program

Private myrray() As String

Now I have problems to redimension this array. I have tried to following

Dim Upper As Integer
Upper = UBound(myArray) ' here I get the runtime error
If Err.Number Then
  Upper = 0
Else
Upper = UBound(myArray) + 1
End If

The problem is that the upper()-function always gives me runtime-error 9 "index outside the valid area

I also tried an other way, here I become the same error but in the else-Block:

Dim Upper As Integer
If IsEmpty(myArray) Then
  Upper = 0
Else
  Upper = UBound(myArray) + 1 'here I get the same error in this line
End If

Later I will use Upper to redimensionze my array like this to add a new value:

ReDim Preserve myArray(Upper)
myArray(Upper) = "new text"

Does anyone know why and how I can solve this problem or tell me an other way to redimensionize an array?

Upvotes: 2

Views: 7374

Answers (1)

Alex K.
Alex K.

Reputation: 175766

(I assume a typo: you declare myrray not myArray)

Private myArray() As String

This gives you an uninitialized array, i.e. one with no dimensions at all & your issue is that you cannot call array functions like UBound/LBound on an array in that state.

Your options are:

  • Set its size to 0 redim myArray(0) when your application starts
  • Detect and handle the uninitialized state and handle it accordingly

Upvotes: 2

Related Questions