在 Excel VBA 中遍历 Table

Iterate through Table in Excel VBA

遍历 table 和 retrieve/store 中每个单元格内容的最佳方法是什么? 使用我目前的方法,我无法在我的变量 val

中设置 table 的值

样本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

你有一个ListObject,使用它的API! ListRowsListColumns 是对象集合,迭代它们的最快方法 by several orders of magnitude 是使用 For Each 循环:

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

如果您只想将内容收集到二维值数组中,则不需要迭代任何内容 - 只需抓住 DataBodyRange 并像对待其他任何东西一样对待它 "regular" Range:

Dim contents As Variant
contents = tbl.DataBodyRange.Value

如果您稍后需要迭代该 2D 变体数组,最快的方法(与上述相同的来源)是 For...Next 循环:

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