【问题标题】:Vba: getting all cells from a given row matching a given stringVba:从给定行中获取与给定字符串匹配的所有单元格
【发布时间】:2019-10-10 22:39:42
【问题描述】:

我得到一排单元格和一个要匹配的字符串。我想知道字符串出现的位置。理想情况下,我需要将它放在 vba 的向量中。

我正在尝试在与变量对应的单元格开始的行上循环所有出现的“匹配名称”。

这是我迄今为止尝试过的:

myIndex = 0
While myIndex < maxIndexAllowed
    myIndex = Match("Name To Match", Offset(Range("beginRowToInspect"), 0, myIndex, 1, maxIndexAllowed), 0) + myIndex
Wend

从概念上讲,这很好。但我收到此错误:“未定义子或函数”并且关键字 Offset 似乎已突出显示。

奖励:如果我能摆脱 maxIndexAllowed,我会很高兴。

【问题讨论】:

  • 您需要知道找到匹配项的每个位置吗?如果是这样,字典是让它快速的方法(如果 UCase/LCase 上没有排列或不完全匹配)
  • @Damian,是的。不知道怎么用。

标签: vba string match offset


【解决方案1】:

试试这个:

Option Explicit
Sub FindAllMatches()

    Dim Matches As New Scripting.Dictionary 'Need the Microsoft Scripting Runtime reference to work
    Dim C As Range
    Dim Col As Byte
    Dim RowToInspect As Long
    Dim NameToMatch As String

    RowToInspect = 2 'here is were you set the row to inspect
    NameToMatch = "x" 'here is were you set your string to match

    With ThisWorkbook.Sheets("MySheet") 'change MySheet for your working sheet
        Col = .Cells(RowToInspect, .Columns.Count).End(xlToLeft).Column 'last column on your row to inspect
        For Each C In .Range(.Cells(RowToInspect, 1), .Cells(RowToInspect, Col))
            If Not Matches.Exists(C.Value) Then
                Matches.Add C.Value, C.Column 'First match we add the item and its column
            Else
                Matches(C.Value) = Matches(C.Value) & "," & C.Column 'Later matches will add the columns separated by ", "
            End If
        Next C
    End With

    If Matches.Exists(NameToMatch) Then
        MsgBox "The columns for " & NameToMatch & " that were found are: " & Matches(NameToMatch)
    Else
        MsgBox NameToMatch & " was not found on row: " & RowToInspect
    End If

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 2021-11-08
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    相关资源
    最近更新 更多