我得到了一行单元格和一个匹配的字符串。我想知道字符串出现的位置。理想情况下,我需要将其放入vba的向量中。
我正在尝试遍历从变量对应的单元格开始的行上所有“要匹配的名称”的出现。
这是我到目前为止尝试过的:
myIndex = 0
While myIndex < maxIndexAllowed
myIndex = Match("Name To Match", Offset(Range("beginRowToInspect"), 0, myIndex, 1, maxIndexAllowed), 0) + myIndex
Wend
从概念上讲这很好。但是,我收到以下错误消息:“未定义子函数或函数”,关键字“偏移”似乎突出显示。
奖金:如果能摆脱maxIndexAllowed,我会很高兴。
答案 0 :(得分: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