您将不得不使用.Find
和.FindNext
。你可以阅读关于它Here。这种方法比拥有大型数据集时循环要快得多。
这是我写得很快的东西。请修改它以适应您的需求。
Sub Find_Cells_Which_Has_My_Damn_String()
Dim WhatToFind As String
Dim aCell As Range, bCell As Range
Dim SearchRange As Range, rng As Range
Dim ws As Worksheet
'~~> Set this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
'~~> Set here what to find
WhatToFind = "1"
'~~> Set this to the relevant range
Set SearchRange = ws.Cells
Set aCell = SearchRange.Find(What:=WhatToFind, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Set bCell = aCell
Set rng = aCell
Do
Set aCell = SearchRange.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
Set rng = Union(rng, aCell)
Else
Exit Do
End If
Loop
End If
If Not rng Is Nothing Then MsgBox rng.Address Else _
MsgBox "No cells were found containing " & WhatToFind
End Sub
截图
你不使用COUNTIF得到相同的结果? – Davesexcel
这是我在VBA的第一个项目,所以我不知道。我会检查它。谢谢! – AOlson
我测试了它,它确实给了我相同的结果,但我需要项目中另一个图层的每个单元的具体位置。 – AOlson