首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Excel VBA中遍历表

在Excel VBA中遍历表
EN

Stack Overflow用户
提问于 2019-06-06 02:15:31
回答 1查看 1.2K关注 0票数 1

遍历表中每个单元格的内容并检索/存储其值的最佳方法是什么?使用我目前的方法,我无法在变量val中获取表的设置值

示例表:

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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-06 03:14:13

你有一个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并将其视为任何其他“常规”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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56465950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档