VBA – search范围内的第一个重复单词

我已经实现了这个macros,如果我运行它,它会在A1:Z20范围内显示单词“needle”的列和行。 虽然如果有多个单词的“针”,它只会输出最后一个。 我怎样才能改变这个代码来显示这个词的第一个出现?

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

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 Next j Next i If found = False Then Range("A25").Value = "needle not found" Range("B25").Value = " " End If End Sub 

没有重复的单词 和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 

进一步详细说明:这个代码实际上做了什么,如果有多个needle实例,它将把find的单元格的所有实例打印到A25:B25中。 比方说,在A1,B2和C3中有3个needle例子。 你的循环将A1打印到A25:B25中,然后是B2,然后是C3。 因为它发生得太快了,所以你只能看到C3或者你所说的“最后的发生”。

你可以做什么来打印出所有的解决scheme(这是我猜你最终要做的),你可以改变你的代码是这样的:

 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

您可以通过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