Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to use code of the following form to populate an array of x rows:

Dim myarray() As Variant
Dim string1 As String

Dim myarray_ubound As Integer
myarray_ubound = 0

For i = 1 to x

  myarray_ubound = myarray_ubound + 1
  ReDim Preserve myarray(1 To myarray_ubound, 1 To 2)

  myarray(myarray_ubound,1) = i
  myarray(myarray_ubound,2) = string1

Next i

However, when I run it it gets stuck after the first loop, telling me that a subscript is out of range. Debugging takes me to the ReDim command.

I used myarray_ubound as an alternative to calling the UBound function many times, but I have tried using this as well and I get the same error.

Can anyone spot what's gone wrong?

share|improve this question
    
decide if you want a one dimensional array or two –  Meehow Aug 4 '14 at 9:23
    
I want two ... is this not? –  apkdsmith Aug 4 '14 at 9:23
    
this can help. –  Ioannis Aug 4 '14 at 9:26

3 Answers 3

up vote 3 down vote accepted

See: http://msdn.microsoft.com/en-us/library/aa266231.aspx "If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all."

Try

ReDim Preserve myarray(1 To 2, 1 To myarray_ubound)

instead.

share|improve this answer

you can only redim the last element of the array (not the first), see below. As you know x I would suggest to redim your array with this value from the beginning.

Dim myarray() As Variant
Dim string1 As String

Dim myarray_ubound As Integer
myarray_ubound = 0

For i = 1 To 10

  myarray_ubound = myarray_ubound + 1
  ReDim Preserve myarray(1 To 2, 1 To myarray_ubound)

  myarray(1, myarray_ubound) = i
  myarray(2, myarray_ubound) = string1

Next i
share|improve this answer

Since you are declaring the variable as a Variant i don't see why you need to re-dim. (maybe related to memory issues, feel free to fill in).

I would suggest:

For i = 1 to 10

myArray(1, i-1) = i
myArray(2, i-1) = string1

next i
share|improve this answer
    
That's a fair comment: the reason is that this is part of a loop so x varies. Thanks for your help. –  apkdsmith Aug 5 '14 at 9:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.