What does ReDim Preserve do?
I am looking at someone else's vba excel code. they are doing ReDim Preserve dataMatrix(7, i)
in both loops. What does this do?
Also, it seems like the second loop just overwrites the data in the first loop, is that correct?
Dim dataMatrix() As String
Worksheets.Item("ETS").Select
Do While Trim(Cells(r, 1)) <> ""
Debug.Print "The line: ", Trim(Cells(r, 1)), r
r = r开发者_Python百科 + 1
dataMatrix(1, i) = Trim(Cells(r, 1)) ''file name
dataMatrix(2, i) = Trim(Cells(r, 2)) ''sample type
dataMatrix(3, i) = Trim(Cells(r, 3)) ''sample name
dataMatrix(4, i) = "ETS" ''
dataMatrix(5, i) = Trim(Cells(r, 5)) ''Response
dataMatrix(6, i) = Trim(Cells(r, 6)) ''ISTD Response
dataMatrix(7, i) = Trim(Cells(r, 10)) ''Calculated Conc
i = i + 1
ReDim Preserve dataMatrix(7, i)
Loop
r = 5
Worksheets.Item("ETG").Select
Do While Trim(Cells(r, 1)) <> ""
Debug.Print "The line: ", Trim(Cells(r, 1)), r
r = r + 1
dataMatrix(1, i) = Trim(Cells(r, 1)) ''file name
dataMatrix(2, i) = Trim(Cells(r, 2)) ''sample type
dataMatrix(3, i) = Trim(Cells(r, 3)) ''sample name
dataMatrix(4, i) = "ETG"
dataMatrix(5, i) = Trim(Cells(r, 5)) ''Response
dataMatrix(6, i) = Trim(Cells(r, 6)) ''ISTD Response
dataMatrix(7, i) = Trim(Cells(r, 10)) ''Calculated Conc
i = i + 1
ReDim Preserve dataMatrix(7, i)
Loop
Redim Preserve
allows you to change the dimensions of an array while keeping the contents of the array.
The Redim Preserve
at the end of each loop is adding another row to the array.
I think the second loop is appending to the array because the i
variable is not changed between the loops.
ReDim
preservers a data in an array when you modify its size. Also it shouldn't overwrite the data becasuse i
is incremented every iteration of the loop: the first loop won't stop until it encounters an empty cell, changing array length every iteration by one, so that when the lenght is 8
it adds 1
to the i
and the new length becomes 9
. When the second iteration occurs it writes the new element to the bound of the array with index 9
, modifies its length again so that it becomes 1
element longer and iterates until encounters an empty line.
精彩评论