VBA - 搜索范围内的第一个重复单词

时间:2017-01-11 09:15:11

标签: excel vba excel-vba

我已经实现了这个宏,如果我运行它,它会显示单词" needle"的单词和行。在A1:Z20范围内。虽然如果有多个单词" needle"它只会输出最后一个。如何更改此代码以显示第一次出现的单词?

希望这是有道理的,到目前为止这是我的代码:

''

With No Repeated Words With 1 Repeated Word

3 个答案:

答案 0 :(得分:1)

如果你只需要第一次出现就退出你的循环!

Sub NeedleSearch()
    Dim SearchSpace As Variant
    Dim found As Boolean
    found = False
    SearchSpace = Range("A1:z20").Value
    Dim i As Integer, j As Integer
    For i = 1 To 20
        For j = 1 To 26
            If SearchSpace(i, j) = "needle" Then
                Range("A25").Value = "Column " & j
                Range("B25").Value = "Row " & i
                found = True
            End If
            If found Then _
                    Exit For
        Next j
        If found Then _
                Exit For
    Next i
    If found = False Then
        Range("A25").Value = "needle not found"
        Range("B25").Value = " "
    End If
End Sub

答案 1 :(得分:0)

进一步详述:这段代码实际上做了什么,如果有needle的多个实例,它会将找到的所有单元格实例打印到A25:B25中。我们假设有needle的3个实例,例如在A1,B2和C3中。你的循环首先将A1打印到A25:B25,然后是B2然后是C3。因为它发生得如此之快,你只能看到C3或你所谓的"最后一次出现"。

你可以做些什么来打印所有解决方案(这是我猜你最后想要做的)你可以将代码更改为这样的代码:

Sub NeedleSearch()
Dim SearchSpace As Variant
Dim found As Boolean
found = False
SearchSpace = Range("A1:z20").Value
Dim ws As Worksheet
Dim i As Integer
Dim j As Integer
Dim k As Integer

Set ws = ThisWorkbook.Sheets(1)
k = 25

For i = 1 To 20
    For j = 1 To 26
        If SearchSpace(i, j) = "needle" Then
            ws.Cells(k, 1).Value = "Occurence " & k - 24
            ws.Cells(k, 2).Value = "Column " & j
            ws.Cells(k, 3).Value = "Row " & i
            k = k + 1
            found = True
        End If
    Next j
Next i
If found = False Then
    ws.Range("A25").Value = "needle not found"
End If
End Sub

相应地更改您的Sheet ID。

HTH

答案 2 :(得分:0)

您可以通过Range对象的Find()方法避免循环:

Option Explicit

Sub NeedleSearch()
    Dim f As Range

    Set f = Range("A1:Z20").Find(what:="needle", LookIn:=xlValues, lookat:=xlWhole, After:=Range("Z20"), SearchOrder:=xlByRows)
    If f Is Nothing Then
        Range("A25").Value = "needle not found"
        Range("B25").Value = " "
    Else
        Range("A25").Value = "Column " & f.Column
        Range("B25").Value = "Row " & f.Row
    End If
End Sub

也可以按如下方式重写:

Sub NeedleSearch()
    Dim f As Range
    Dim arr As Variant

    Set f = Range("A1:Z20").Find(what:="needle", LookIn:=xlValues, lookat:=xlWhole, After:=Range("Z20"), SearchOrder:=xlByRows)
    If f Is Nothing Then
        arr = Array("needle not found", " ")
    Else
        arr = Array("Column " & f.Column, "Row " & f.Row)
    End If
    Range("A25:B25").Value = arr
End Sub