如何查找列标题并返回列号vba

时间:2020-02-26 00:56:45

标签: excel vba

我要在工作表的第一行“ Reference”中查找特定的列标题,并写成这样:

colnum = Application.WorksheetFunction.Match("Reference", 1:1,0)

但是,这表示我的语法有问题。我不确定是怎么了。有人可以更正此错误,以便在工作表的第一行中找到标题“ Reference”时返回正确的列号。

3 个答案:

答案 0 :(得分:0)

尝试以下子项。

Sub FindHeader()
Dim sht As Worksheet
Dim Rng As Range

    Set sht = Worksheets("Sheet1") ' Define your desired sheet
    Set Rng = sht.Cells.Find("Reference") 'Find your desired value/text

        If Not Rng Is Nothing Then 'If found then do operation
            MsgBox Rng.Column 'You can do other actions here instead of messagebox
        Else
            MsgBox "Nothing found"
        End If

    Set sht = Nothing 'Clear memory
    Set Rng = Nothing

End Sub

答案 1 :(得分:0)

尝试

colnum = Application.WorksheetFunction.Match("Reference", _
         Worksheets("Reference").Rows(1), 0)

但是请记住,如果找不到匹配项,则会出现错误。您将必须进行适当的错误处理。例如

colnum = "Not Found"
On Error Resume Next
colnum = Application.WorksheetFunction.Match("Reference", _ 
         Worksheets("Reference").Rows(1), 0)
On Error GoTo 0

Debug.Print colnum

以上显然将无法处理工作表名称错误。为此,您可以使用类似的

     On Error GoTo Whoa

     colnum = Application.WorksheetFunction.Match("Reference", _
              Worksheets("Reference").Rows(1), 0)

LetsContinue:
     Debug.Print colnum

     Exit Sub
Whoa:
     colnum = Err.Description
     Resume LetsContinue

您也可以尝试.Evaluate以获得一种衬垫解决方案

Application.Evaluate("=IFERROR(MATCH(""Reference"",Reference!1:1,0),""Not Found"")")

PS :顺便说一句,我对.Find略有偏见:)

答案 2 :(得分:-2)

在这里完成了VBA新手,但是您可能拼错了“列”?你写了“ colnum” 请忽略是否与它完全无关