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

时间:2016-07-14 18:15:17

标签: excel vba excel-vba

我在Excel,New Sheet和Old Sheet中有两个工作表。如果列包含新工作表A列的每个条目,我试图在旧工作表的A列中搜索。我使用以下VBA代码进行搜索,但它在第二次搜索时返回错误(非列标题搜索)。我不知道我做错了什么 - 感谢任何帮助。这是我的代码:

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' - 对象'Range'的方法'Find'失败。

2 个答案:

答案 0 :(得分:1)

避免使用.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

这对你有用吗?我在我的测试它,它的工作。确保您提供的范围是正确的。

但是,我同意@ScottHoltzman - 您可以使用条件格式化来避免使用VBA。

答案 1 :(得分:0)

感谢大家的帮助。

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

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

适用于“新一号”中的A栏。工作表。