簡體   English   中英

如何查找列標題並返回列號vba

[英]how to find column header and return column number vba

我正在尋找名為“參考”的工作表的第一行中的特定列標題並寫道:

colnum = Application.WorksheetFunction.Match("Reference", 1:1,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

嘗試

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 :)

在這里完成 VBA 菜鳥,但您可能拼錯了“列”? 你寫了'colnum' 如果這與它完全無關,請無視

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM