vba ReDim Preserve 有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2916009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does ReDim Preserve do?
提问by l--''''''---------''''''''''''
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?
我在看别人的 vba excel 代码。他们ReDim Preserve dataMatrix(7, i)在两个循环中都在做。这有什么作用?
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 + 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
采纳答案by Yasir Arsanukaev
ReDimpreservers a data in an array when you modify its size. Also it shouldn't overwrite the data becasuse iis 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 8it adds 1to the iand 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 1element longer and iterates until encounters an empty line.
ReDim当您修改其大小时,将数据保留在数组中。此外,它不应该覆盖数据i,因为循环的每次迭代都会增加:第一个循环不会停止,直到遇到空单元格,每次迭代都将数组长度更改为一个,以便当长度为时,8它会添加1到i和新长度变为9. 当第二次迭代发生时,它将新元素写入具有 index 的数组的边界,9再次修改其长度以使其成为1更长的元素并迭代直到遇到空行。
回答by aphoria
Redim Preserveallows you to change the dimensions of an array while keeping the contents of the array.
Redim Preserve允许您在保留数组内容的同时更改数组的维度。
The Redim Preserveat the end of each loop is adding another row to the array.
的Redim Preserve在每个循环结束时加入另一行到阵列。
I think the second loop is appending to the array because the ivariable is not changed between the loops.
我认为第二个循环附加到数组,因为i变量在循环之间没有改变。

