Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

vba - 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 + 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...