输入参数并返回列索引会很有用。有什么解决办法吗?
这是可行的版本,但一次只能输入一个 colName 值来更改索引值,并且对于重复应用没有太大价值。
colName = "Inv#"
colIndex = Worksheets("Invoice Database").ListObjects("Table2").ListColumns(colName).Range(1, 1).Column
MsgBox (colIndex) 'returns column index of 1
以下是一个假设的解决方案,无需在每个实例中声明 colName 字符串。
colIndex(colName) = Worksheets("Invoice Database").ListObjects("Table2").ListColumns(colName).Range(1, 1).Column
msgBox (colIndex("Inv#")) 'returns column index of 1
msgBox (colIndex("Full Name)) 'returns column index of 2
msgBox (colIndex("Service Date)) 'returns column index of 3
您可以创建这样的函数
Public Function colIndex(colName As String) As Long
Dim lo As ListObject
Set lo = Worksheets("Invoice Database").ListObjects("Table2")
colIndex = lo.ListColumns(colName).Index
End Function
然后像这样使用它:
Sub test()
MsgBox colIndex("Inv#")
MsgBox colIndex("Full name")
End Sub