在特定的表格中search

我有这个macros,我不能让它执行search只在特定的表(本例中的“aaa”,“bbb”,“ccc”)。\当前代码返回MsgBox“没有紫色字段find”,即使我把它在其中一个故意单。 我也将我的macrosselect并显示第一个find的单元格(即使目前其他表打开)。 请帮忙。

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 

只需search整个工作簿,然后检查是否在相关工作表中。 这是一个例子

 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和.FindNext在Excel VBA中解释.Find.FindNext如何工作。

不幸的是,你不能将不同的纸张的范围合并成一个。

下面的问题是相当相关的,并给出了一个很好的解释: VBA:如何将两个不同的工作表范围合并为一个循环

正如上面的链接所build议的,我会循环访问您的工作表并在最后附加结果。