【发布时间】:2017-01-06 13:23:17
【问题描述】:
我正在使用从该网站获得的代码Find All Instances With VBA。一切正常,但由于某种原因,它从第二次出现循环到文件末尾,然后获得第一次。
例如:
-- 样本数据:
Origin X Y
S 45 65
W 78 7
S 45 5
D 6 3
B 75 68
S 19 87
T 23 98
S 33 94
Q 21 105
S 17 117
T 12 128
当我尝试在字母“S”的来源列中查找所有出现时,我通过Debug.Print (rng.Address) 检索地址,它将提供$A$4,$A$7,$A$9,$A$11,$A$2。
为什么最后显示 $A$2?这发生在我所有不同的 excel 文件中。
代码如下:
Sub FindAll()
'PURPOSE: Find all cells containing a specified values
'SOURCE: www.TheSpreadsheetGuru.com
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
'What value do you want to find (must be in string form)?
fnd = "S"
Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
GoTo NothingFound
End If
Set rng = FoundCell
'Loop until cycled through all unique finds
Do Until FoundCell Is Nothing
'Find next cell with fnd value
Set FoundCell = myRange.FindNext(after:=FoundCell)
'Add found cell to rng range variable
Set rng = Union(rng, FoundCell)
'Test to see if cycled through to first found cell
If FoundCell.Address = FirstFound Then Exit Do
Loop
'Select Cells Containing Find Value
rng.Select
Debug.Print (rng.Address)
Exit Sub
'Error Handler
NothingFound:
MsgBox "No values were found in this worksheet"
End Sub
【问题讨论】:
-
Cells(myRange.Cells.Count)如果范围不相交,可能无法获取最后一个单元格 -
感谢您的信息。我的实际数据是不相交的,但这个样本还没有,它仍然始终提供第一个。
-
我上真机后试试你的代码...