查找给定字符串的单元格列

Find Cell's Column Given String

我正在尝试查找包含字符串 "Status" 的单元格的列。该单元格位于另一个名为 "Report" 的 sheet 中,我不知道该单元格在哪里;我只确切地知道它包含什么。我只需要知道单元格所在的列。我将如何着手执行此操作(在 VBA 中)?任何帮助将不胜感激!到目前为止我的代码如下:

Sheets("Report").Select
Dim header_cell As Variant
Set header_cell = Cells.Find(what:="Status")

如果你创建一个新变量,说“dim header_cell_column as Integer”;你可以做到

header_cell_column = Cells.Find(what:="Status").Column

还有,

Sub Button1_Click()
    Dim sh As Worksheet, lookRng As Range, c As Range
    Set sh = Sheets("Report")
    Set lookRng = sh.Range("A1:Z1")

    Set c = lookRng.Find(what:="Status", lookat:=xlWhole)

    If Not c Is Nothing Then
        MsgBox c.Address
    Else: MsgBox "Not Found"
        Exit Sub
    End If


End Sub

我建议您避免激活工作表以便使用它。

    Dim header_cell As Range
    With Sheets("Report")
        'this searches just row 1
        'Set header_cell = .Rows(1).Find(what:="Status", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        'this searches the whole worksheet
        Set header_cell = .Cells.Find(what:="Status", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        Debug.Print header_cell; "Column: " & header_cell.Column
        Debug.Print header_cell; "Address: " & header_cell.Address(0, 0, ReferenceStyle:=xlA1, external:=True)
    End With

有关摆脱依赖 select 和激活的方法的更多信息,请参阅 How to avoid using Select in Excel VBA macros