在Excel VBA中查找多个值

我想突出显示excel文件中所有可能的值。 然而,我的代码只突出显示了每张纸的第一个find的值,但是我想突出显示每个find的值。 我猜“FindNext”不能正常工作,因为我希望它能正常工作。 我尝试了其他来自互联网的其他示例,其中显示了相同的结果。 出了什么问题?

Sub test() Dim counter As Integer Dim currentSheet As Integer Dim cell As Range On Error Resume Next currentSheet = ActiveSheet.Index datatoFind = StrConv(InputBox("Please enter the value to search for"), vbLowerCase) If datatoFind = "" Then Exit Sub sheetCount = ActiveWorkbook.Sheets.Count If IsError(CDbl(datatoFind)) = False Then datatoFind = CDbl(datatoFind) For counter = 1 To sheetCount Sheets(counter).Activate Set cell = Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) If Not cell Is Nothing Then FirstAddress = cell.Address Do cell.Interior.Color = RGB(255, 0, 0) cell = Cells.FindNext(After:=cell) Loop Until cell.Address = FirstAddress End If Next counter End Sub 

作为后续评论这一个作品(代码slighlty改进):

 Sub test() Dim cell As Range Dim ws As Worksheet Dim datatoFind Dim FirstAddress As String datatoFind = StrConv(InputBox("Please enter the value to search for"), vbLowerCase) If datatoFind = "" Then Exit Sub If IsNumeric(datatoFind) Then datatoFind = CDbl(datatoFind) For Each ws In ActiveWorkbook.Worksheets With ws.Cells Set cell = .Find(What:=datatoFind, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, _ MatchCase:=False, SearchFormat:=False) If Not cell Is Nothing Then FirstAddress = cell.Address Do cell.Interior.Color = RGB(255, 0, 0) Set cell = .FindNext(cell) If cell Is Nothing Then Exit Do Loop Until cell.Address = FirstAddress End If End With Next ws End Sub 

你的Loop Until cell.Address = FirstAddress触发一个错误,当cell没有什么,这就是为什么我joinIf cell Is Nothing Then Exit Do (你没有看到这个错误消息,因为你使用On Error Resume Next

另外两个有趣的读:

  1. 为什么我应该明智地使用On Error Resume Next
  2. 如何避免使用Select / Active语句