2

Suppose I have a code like this:

Dim resultArray() As Double
ReDim resultArray(1 to 10) As Double

Dim i As Integer
For i = 1 to 10 
  resultArray(i) = i
Next

ReDim resultArray(1 to 20) As Double
For i = 11 To 20
 resultArray(i) = i
Next

Is code like this possible? Would the values from the first cycle remain in the array?

I don't know the length of an array. 20 is just a number, which I won't know until the very end of the program.

Community
  • 1
  • 1
parsecer
  • 4,758
  • 13
  • 71
  • 140

2 Answers2

5

You can do this by ReDim Preserve This however will only allow you to change the outside length of the array. However, if you do know the maximum size of an array (as you do here) it would be best to Dim it at the maximum size. You can always decrease the size of the array at the end using ReDim Preserve as well if needs be.

Dim resultArray() As Double
ReDim resultArray(1 to 10) As Double

Dim i As Integer
For i = 1 to 10 
  resultArray(i) = i
Next

ReDim Preserve resultArray(1 to 20) As Double
For i = 11 To 20
 resultArray(i) = i
Next
Tom
  • 9,725
  • 3
  • 31
  • 48
4

Use the Preserve keyword

  ReDim Preserve resultArray(1 to 20) As Double
Harassed Dad
  • 4,669
  • 1
  • 10
  • 12