2016-09-23 52 views
2

我有一个名为“指示”的excel工作表在其中包含我的宏的Excel表“工具”在同一目录中。 Excel表单有大约400行和20列的数据。搜索一个字符串,并找到相邻列的内容

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

我必须在D列的Excel表格“指示”中搜索该字符串输入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 
+0

您不介意透露工作表的名称...? – Jeeped

+0

在复制代码时忘记更改它。感谢您提醒我 – S6633d

+0

您的代码和叙述混淆了术语**工作簿**和**工作表**。 [工作簿对象](https://msdn.microsoft.com/en-us/library/office/ff835568.aspx)与[工作表对象](https://msdn.microsoft.com/ EN-US /图书馆/办公室/ ff194464.aspx)。 – Jeeped

回答

1

有单一列lookat:=xlWhole比赛,我更喜欢使用Excel Application objectMATCH 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可以轻松地从任何一列在同一行返回值。

+0

请注意,搜索字词必须与整个单元格值匹配,但不区分大小写。 – Jeeped

+0

无法将该值分配给Dim value1作为字符串,设置value1 = Debug.Print .Cells(rw,“Q”)。Value – S6633d

+0

使用'dim str作为字符串'然后'str = .Cells(rw,“ Q“)。Value'。你只需要设置对象;你不需要它来分配一个字符串值。看到我上面的编辑。 – Jeeped

相关问题