Iterate through Table in Excel VBA

久未见 提交于 2019-12-11 06:37:02

问题


What is the best way to iterate through the contents of each cell in a table and retrieve/store its value. With my current approach, I'm unable to obtain set the value of a table in my variable val

Sample Table:

Set ws = ActiveSheet
ws.Name = "sheet1"

Set tbl = ws.ListObjects("tblBor")
Application.Calculation = xlCalculationManual
ws.Calculate

With tbl.Sort
         .SortFields.Clear
         .SortFields.Add Key:=Range("tblBor[ID]"), SortOn:=xlSortOnValues, Order:=xlAscending
         .Header = xlYes
         .Apply
End With

Set rng = Range(tbl)
rows = tbl.Range.rows.Count
Columns = tbl.Range.Columns.Count

For iter = 1 To rows
    For col = 1 To Columns
        'Iterate through each row by each column
        'val = tbl.DataBodyRange(iter, col).Value

    Next col
Next iter

回答1:


You have a ListObject, use its API! ListRows and ListColumns are object collections, and the fastest way to iterate these, by several orders of magnitude, is with a For Each loop:

Dim tblRow As ListRow
For Each tblRow In tbl.ListRows
    Dim tblCol As ListColumn
    For Each tblCol In tbl.ListColumns
        Debug.Print "(" & tblRow.Index & "," & tblCol.Index & "): " & tblRow.Range(tblCol.Index).Value
    Next
Next

If you just want to collect the contents into a 2D array of values, you don't need to iterate anything - just grab the DataBodyRange and treat it like any other "regular" Range:

Dim contents As Variant
contents = tbl.DataBodyRange.Value

If you later need to iterate that 2D variant array, the fastest way (same source as above) is For...Next loops:

Dim currentRow As Long
For currentRow = LBound(contents, 1) To UBound(contents, 1)
    Dim currentCol As Long
    For currentCol = LBound(contents, 2) To UBound(contents, 2)
        Debug.Print "(" & currentRow & "," & currentCol & "): " & contents(currentRow, currentCol)
    Next
Next


来源:https://stackoverflow.com/questions/56465950/iterate-through-table-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!