我有这个宏,我不能让它只在特定的表格中进行搜索(" aaa"," bbb"," ccc"在这种情况下)。\ 当前代码返回MsgBox"未找到紫色字段"即使我故意把它放在其中一张纸上。 我也想我的宏选择并显示第一个找到的单元格(即使当前其他工作表已打开)。 请帮忙。
Dim cell As Range
Dim SearchRange As Range
Dim c As Range
Dim shtfound As Boolean
sthfound = False
On Error Resume Next
Set SearchRange = ThisWorkbook.Worksheets(Array("bbb", "aaa", "ccc")).UsedRange.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not SearchRange Is Nothing Then
With Application.FindFormat.Interior
.PatternColorIndex = xlAutomatic
.Color = 16711935
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Set c = SearchRange.Find(What:="", After:=SearchRange.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=True)
If Not c Is Nothing Then
firstAddress = c.Address
Set foundrange = c
Do
Set c = SearchRange.Find(What:="", After:=c, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=True)
Set foundrange = Union(foundrange, c)
Loop While Not c Is Nothing And c.Address <> firstAddress
foundrange.Activate
sthfound = True
MsgBox "Purple fields found: " & foundrange.Count
End If
End If
If sthfound = False Then MsgBox "No purple field found"
End Sub
答案 0 :(得分:2)
只需搜索整个工作簿,然后检查它是否在相关工作表中。这是一个例子
Sub Sample()
Dim ws As Worksheet
Dim aCell As Range, bCell As Range
Dim searchString As String
'~~> This is your search string
searchString = "Sid"
'~~> Loop through the worksheet
For Each ws In ThisWorkbook.Worksheets
Set aCell = ws.Cells.Find(What:=searchString, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
'~~> If found
If Not aCell Is Nothing Then
'~~> Check if it is in the sheet we want
Select Case aCell.Parent.Name
Case "aaa", "bbb", "ccc"
MsgBox "Found in Sheet " & aCell.Parent.Name
Set bCell = aCell
'~~> Find other occurances
Do
Set aCell = ws.Cells.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
MsgBox "Found in Sheet " & aCell.Parent.Name
Else
Exit Do
End If
Loop
End Select
End If
Next
End Sub
注意:您可能希望看到.Find and .FindNext In Excel VBA,其中说明了.Find
和.FindNext
的工作原理。
答案 1 :(得分:1)
不幸的是,您无法将不同工作表的范围合并为一个。
以下问题非常相关,并给出了一个很好的解释: VBA: How to combine two ranges on different sheets into one, to loop through
正如上面的链接中所建议的那样,我会循环浏览您的工作表并在最后添加结果。