如何在 excel VBA 中引用名为 table 的列?

How to reference named table column in excel VBA?

将项目 属性 与单元格 属性 一起使用的语法如下:

Cells.Item(Row,Column)

行必须使用数值,但列可以使用数值或字符串值。以下两行均引用单元格 C5:

Cells(5,"C")
Cells(5,3)

因为Item属性是RANGE对象的默认属性,你可以缩短这些行如下:

Cells(5,"C")
Cells(5,3)

我最近发现你可以这样做:

For Each cell In Range("A2:A3")
Cells(cell.Row,3)

我该怎么做(我需要正确的语法)

For Each cell In Range("A2:A3")
Cells(cell.Row,cell.Row.NamedColumn"Customer")

一种方法是在 header 行中搜索要使用的列名称。返回的范围 object 的列 属性 表示您要使用的列。请参阅下面的代码,如果您需要其他帮助,请告诉我们。

Sub LocateByHeader()
    Dim rngFnder As Range
    Dim rngHeader As Range

    Const HEADER_ROW As Integer = 1

    Set rngHeader = Intersect(Sheet1.Rows(HEADER_ROW), Sheet1.UsedRange)

    Set rngFnder = rngHeader.Find("Customer")

    If rngFnder Is Nothing Then
        'Do some code in  case the header isn't there
    Else
        ' rngFnder.Column will give the index of the column with the customer name
    End If

End Sub

您应该 select 列 E 并为其分配一个 range name CUSTOMER。然后,您可以在代码中将其引用为 Range("CUSTOMER"),并将其列号引用为 Range("CUSTOMER").Column。如果您剪切此列并将其粘贴到其他位置,它的名称将随之而来,因此代码中的引用将保持有效。