在Range.Find找不到任何内容之后,VBA返回错误

我在Excel,新表和旧表中有两个工作表。 如果列中包含新工作表A列的每个条目,我正试图在旧工作表的A列中进行search。 我正在使用下面的VBA代码进行search,但它在第二个search(非列标题search)上返回一个错误。 我不知道我在做什么错 – 任何帮助表示赞赏。 这是我的代码:

Sub Sample() Dim lastRow As Integer Dim i As Integer Dim rng As Range Dim searchrng As Range Dim searchval As String lastRow = Sheets("New One").Range("A65000").End(xlUp).Row Sheets("Old One").Activate Set searchrng = Sheets("Old One").Range("A1:A10000") For i = 1 To lastRow Sheets("New One").Activate searchval = Sheets("New One").Cells(i, 1).Value Set rng = searchrng.Find(searchval) If Not rng Is Nothing Then MsgBox "Found " & searchval & " in " & rng.Address Else Sheets("New One").Activate Sheets("New One").Cells(i, 1).EntireRow.Interior.Color = vbRed End If Next i End Sub 

该错误始终是运行时错误“1004” – 对象'范围'的方法'查找'失败。

避免使用。select

 Sub Sample() Dim lastRow As Integer Dim i As Integer Dim rng As Range Dim searchrng As Range Dim searchval As String Dim oldWS As Worksheet, newWS As Worksheet Set oldWS = Worksheets("Old One") Set newWS = Worksheets("New One") lastRow = newWS.Range("A65000").End(xlUp).Row Set searchrng = oldWS.Range("A1:A10000") For i = 1 To lastRow searchval = newWS.Cells(i, 1).Value Set rng = searchrng.Find(searchval) If Not rng Is Nothing Then MsgBox "Found " & searchval & " in " & rng.Address Else newWS.Cells(i, 1).EntireRow.Interior.Color = vbRed End If Next i End Sub 

那对你有用吗? 我在我的testing,它的工作。 确保你给的范围是正确的。

但是,我同意@ScottHoltzman – 你可以使用条件格式来做到这一点,避免使用VBA。

感谢大家的帮助。

我能够通过条件格式来实现它,感谢Scott Holtzman的想法。 最后,我使用了COUNTIF,而不是IsError。

 =COUNTIF('Old One'!$A:$A, 'New One'!$A1)=1 

应用于“新build”工作表中的A列。