vba 在Excel中按单元格值获取列号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14942758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get column number by cell value in Excel
提问by Beez
I'm trying to get the column number of a cell in the first row with a specific value. The code I'm using isn't working for some reason.
我正在尝试使用特定值获取第一行中单元格的列号。我使用的代码由于某种原因不起作用。
Dim colNum As Integer
'sheetName is a String
With ActiveWorkbook.Sheets(sheetName)
colNum = column(.Match("ID", 1:1, 0))
It's telling me it's expecting a "list separator or )". How do I make it work?
它告诉我它需要一个“列表分隔符或 )”。我如何使它工作?
Thanks
谢谢
回答by Peter L.
Try this code:
试试这个代码:
Dim colNum As Integer
'sheetName is a String
colNum = WorksheetFunction.Match("ID", ActiveWorkbook.Sheets(sheetname).Range("1:1"), 0)
回答by D_Bester
Note that if the match is not found it will return an error; try this to handle that.
请注意,如果未找到匹配项,它将返回错误;试试这个来处理那个。
Dim Result As Variant
If Not VBA.IsError(Application.Match(...)) Then
Result = Application.Match(...)
End If
This tries the match and if there is an error on the function it will not assign a result.
这会尝试匹配,如果函数出现错误,则不会分配结果。