【问题标题】:searching a string and finding content of adjacent column搜索字符串并查找相邻列的内容
【发布时间】:2016-09-23 04:13:31
【问题描述】:

我在包含我的宏的 excel 表“工具”所在的同一目录中有一个名为“indications”的 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

【问题讨论】:

  • 您不想透露工作表的名称...?
  • 复制代码时忘记更改它。谢谢你提醒我
  • 您的代码和叙述混淆了术语 workbookworksheetWorkbook ObjectWorksheet Object 不同。

标签: vba excel match


【解决方案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 就可以轻松返回同一行中任意列的值。

【讨论】:

  • 请注意,搜索词必须与整个单元格值匹配,但不区分大小写。
  • 我不能将该值分配给像 Dim value1 As String 这样的变量,设置 value1 = Debug.Print .Cells(rw, "Q").Value
  • 使用dim str as string 然后str = .Cells(rw, "Q").Value。你只需要Set对象;您不需要它来分配字符串值。请参阅上面的编辑。
  • True Match 对于单列 xlWhole 搜索要快得多 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
相关资源
最近更新 更多