查找Cell的列给定字符串

时间:2015-05-15 20:14:37

标签: excel vba excel-vba excel-2010

我正在尝试查找包含字符串" Status"的单元格的列。该单元格位于另一张名为" Report"我不知道细胞在哪里;我只知道它包含的内容。我需要知道的是单元格所在的列。我将如何进行此操作(在VBA中)?任何帮助将不胜感激!到目前为止我的代码如下:

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

3 个答案:

答案 0 :(得分:3)

我建议您不要激活工作表以便使用它。

    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和activate的方法的更多信息,请参阅How to avoid using Select in Excel VBA macros

答案 1 :(得分:2)

同样,

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

答案 2 :(得分:1)

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

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