VBA - 循环遍历表并使用列名更新另一列

时间:2017-08-31 11:15:48

标签: vba excel-vba excel

在Excel VBA中,我尝试遍历Excel表,然后更新该行中的另一列。我希望通过名称而不是偏移/数字来引用另一列,以防布局发生变化。这可能吗?

Dim rw As ListRow
Dim cl As Range

For Each rw In ActiveSheet.ListObjects("MasterData").ListRows
    'Pseudo code:
     if (rw[Notes] = "Test") then DO SOMETHING 'In this line I'd like to refer to the column called "Notes" but not sure how to do it.
Next rw

1 个答案:

答案 0 :(得分:0)

Intersect function将完成约90%的工作。其余的是这样的:

Option Explicit

Sub TestMe()

    Dim rw          As Range
    Dim cl          As Range
    Dim rngCell     As Range

    For Each rw In [MyTable].Rows
        Set rngCell = Intersect(rw, [MyColumnName])
        If Not rngCell Is Nothing Then
            If rngCell = "Text" Then Debug.Print rngCell.Address
        End If
    Next rw

End Sub
  • [MyTable] 是表格的名称。
  • [MyColumnName] 是列的名称。