搜索字符串并查找相邻列

时间:2016-09-23 04:13:31

标签: excel vba excel-vba match

我在同一目录中有一个名为“indications”的excel表,其中包含我的宏的excel表“工具”。 Excel工作表指示有大约400行和20列数据。

我有一个宏,它将从用户那里获取一个字符串输入(例如:DUMMY_TEXT)并运行另一个宏。另一个宏是我被击中的地方。

我必须在D列的excel表“indication”中搜索该字符串输入DUMMY_TEXT,并找到找到字符串输入的相应行中Q,R,S和T列的内容。这必须根据用户输入动态发生。

我很震惊地发现了Q,R,S和T列的内容。这就是我现在所拥有的

Dim FoundCell As Excel.Range

temppath = ActiveWorkbook.Path
Workbooks.Open (temppath + "\indications.xlsx")

Set FoundCell = Range("D1:D20000").Find(what:=LSearchValue, lookat:=xlWhole)

Workbooks("indications.xlsx").Close

1 个答案:

答案 0 :(得分:1)

对于单个列中的lookat:=xlWhole匹配,我更倾向于Excel Application object使用MATCH function而不是Range.Find method

Sub trwqoeiryg()
    Dim findThis As Variant, rw As Variant, wb As Workbook
    Dim strQ as string, strR as string, strS as string, strT as string
    findThis = "find This"

    'VB/VBA uses an ampersand as the preferred string concatenation operator
    Set wb = Workbooks.Open(Filename:=temppath & "\Indications.xlsx", ReadOnly:=True)

    With wb
        With .Worksheets(1)   '<~~set this properly!
            rw = Application.Match(findThis, .Columns("D"), 0)
            If Not IsError(rw) Then
                Debug.Print .Cells(rw, "Q").Value
                Debug.Print .Cells(rw, "R").Value
                Debug.Print .Cells(rw, "S").Value
                Debug.Print .Cells(rw, "T").Value
                strQ = .Cells(rw, "Q").Value
                strR = .Cells(rw, "R").Value
                strS = .Cells(rw, "S").Value
                strT = .Cells(rw, "T").Value
                Debug.Print strQ
                Debug.Print strR
                Debug.Print strS
                Debug.Print strT
            Else
                Debug.Print findThis & " not found."
            End If
        End With
        .Close SaveChanges:=False
    End With
End Sub

通过MATCH返回的行号后,Range.Cells property可以轻松地从同一行的任何列返回值。

相关问题