Заполните двумерный массив одним циклом - PullRequest
0 голосов
/ 10 марта 2019

Я попробовал приведенный ниже код, чтобы заполнить двумерный массив в Excel VBA, и мне удалось получить желаемые результаты.Я хотел бы знать, есть ли лучший способ сделать это или вы предвидите какие-либо технические проблемы, когда у меня будет значительно больший объем данных в реальных ситуациях.Любые идеи или предложения будут оценены для улучшения.

Sub test_selection()
' My below array is based on values contained within
' selected cells
' The purpose of using two dimensional array is to 
' keep values in one column of array 
' while retaining cell addresses in 2nd 
' dimension to print some info in relevant cells
' offset to the selected cells

Dim anArray() As String

firstRow = Selection.Range("A1").Row
LastRow = Selection.Rows(Selection.Rows.Count).Row
colum = Selection.Columns.Column
arrSize = LastRow - firstRow

ReDim anArray(0 To arrSize, 1)
cnt = 0

For i = firstRow To LastRow
    anArray(cnt, 0) = CStr(Cells(i, colum).Value2)
    anArray(cnt, 1) = Cells(i, colum).Address
    cnt = cnt + 1
Next i

Call TestGetFileList(anArray)

End Sub

1 Ответ

1 голос
/ 10 марта 2019

Если у вас значительно больший размер данных , этот цикл по рабочему листу будет медленным. Вероятно, лучше получить все данные сразу и обработать их в памяти.

Option Explicit

Sub test_selection()
' My below array is based on values contained within
' selected cells
' The purpose of using two dimensional array is to
' keep values in one column of array
' while retaining cell addresses in 2nd
' dimension to print some info in relevant cells
' offset to the selected cells

    Dim i As Long, r As Long, c As String, anArray As Variant

    With Selection
        c = Split(.Cells(1).Address, "$")(1)
        r = Split(.Cells(1).Address, "$")(2) - 1
        anArray = .Columns(1).Cells.Resize(.Rows.Count, 2).Value2
    End With

    For i = LBound(anArray, 1) To UBound(anArray, 1)
        anArray(i, 1) = CStr(anArray(i, 1))
        anArray(i, 2) = "$" & c & "$" & i + r
    Next i

    TestGetFileList anArray

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...