在Excel中匹配第N个实例

时间:2016-06-06 18:28:43

标签: excel vba

我在电子表格上使用匹配功能,电子表格具有相同的关键字但在不同的行中,我试图获取行号并执行此操作我想使用关键字的第二个实例。如何在VBA中完成我当前的代码

Application.WorksheetFunction.Match("Hello", Range("A1:A100"), 0)

我在考虑使用Index功能,但我不确定如何使用它。

3 个答案:

答案 0 :(得分:2)

在第一个下方开始第二次匹配:

Sub dural()
    Dim rw As Long

    With Application.WorksheetFunction
        rw = .Match("Hello", Range("A1:A1000"), 0)
        rw = .Match("Hello", Range("A" & (rw + 1) & ":A1000"), 0) + rw
        MsgBox rw
    End With
End Sub

enter image description here

如果你想要N th 匹配,我会使用 Find() FindNext()循环。

修改#1:

找到N th 实例的另一种方法是 Evaluate() VBA中的典型数组公式。对于 N = 3 ,在工作表中,数组公式为:

=SMALL(IF(A1:A1000="Hello",ROW(A1:A1000)),3)

所以使用VBA:

Sub dural()
    Dim rw As Long, N As Long

    N = 3
    rw = Evaluate("SMALL(IF(A1:A1000=""Hello"",ROW(A1:A1000))," & N & ")")
    MsgBox rw
End Sub

答案 1 :(得分:1)

以下是使用Range.Find的方法。

Option Explicit
Sub FindSecond()
    Dim rSearch As Range, C As Range
    Const sSearchFor As String = "Hello"
    Dim sFirstAddress As String

Set rSearch = Range("A1:A100")

With rSearch  'Note that search starts at the bottom
    Set C = .Find(what:=sSearchFor, after:=rSearch(.Rows.Count, 1), _
        LookIn:=xlValues, lookat:=xlWhole, searchorder:=xlByRows, _
        searchdirection:=xlNext, MatchCase:=False)
    If Not C Is Nothing Then
        sFirstAddress = C.Address
        Set C = .FindNext(C)
        If C.Address <> sFirstAddress Then
            MsgBox "2nd instance of " & sSearchFor & " on row " & C.Row
        Else
            MsgBox "Only one instance of " & sSearchFor & " and it is on row " & C.Row
        End If
    Else
        MsgBox "No instance of " & sSearchFor
    End If
End With
End Sub

enter image description here

答案 2 :(得分:0)

可能有更好的方法,但这有效:

=MATCH("Hello",INDIRECT("A"&(1+MATCH("Hello",A1:A100,0))&":A100"),0)

这将返回第二次出现的索引,方法是搜索第一次出现并使用它来定义搜索下一次出现的范围。