在Excel VBA中遍历表格

时间:2019-06-05 18:15:30

标签: excel vba listobject

迭代表中每个单元格的内容并检索/存储其值的最佳方法是什么。 使用目前的方法,我无法在变量val

中获取表的设置值

样品表:

enter image description here

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 个答案:

答案 0 :(得分:1)

您有一个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

如果您只想将内容收集到2D值数组中,则无需进行任何迭代-只需抓住DataBodyRange并将其像其他“常规” 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