Excel VBA查找函数获取运行时错误1004

时间:2016-06-21 14:22:23

标签: excel vba

每次我尝试运行此代码时都会收到此错误: '运行时错误1004:应用程序定义或对象定义错误' 它特别不喜欢“查找”功能,没有它,它运行正常。

我的代码如下:

Public Sub main()
    Dim maxVal As Long
    Dim origValue As Long
    Dim CaseNumber As Long
    Dim FoundCell As Range

maxVal = Range("A1").End(xlDown).Row
For origValue = 2 To maxVal
    CaseNumber = Sheets("Complications").Cells(origValue, 1).Value
    FoundCell = Sheets("Complications").Cells.Range(a1, a50000).Find(What:=CaseNumber)
    If FoundCell Is Nothing Then
        Sheets("Complications").Cells(origValue, 1).Value = Sheets("Cases").Cells(origValue, 1).Value
    Else
    End If

    Next
End Sub

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

Set FoundCell = Sheets("Complications").Cells.Range("A1:A50000").Find(What:=CaseNumber)

您输入的范围不正确。

答案 1 :(得分:1)

作为Bruce Wayne对您问题的回答,以下内容可以帮助您避免将来可能出现的问题:

Public Sub main()
    Dim maxVal As Long
    Dim origValue As Long
    Dim FoundCell As Range

    With Worksheets("Complications") '<--| reference this sheet once and for all and rest assure you're dealing with it if not otherwise explicitly referenced
        maxVal = .Range(.Rows.Count, 1).End(xlUp).Row '<--| find the "real" last non blank cell in column A, should any blank cell precede before it
        For origValue = 2 To maxVal
            Set FoundCell = .Range("A1", "A50000").Find(What:=.Cells(origValue, 1).Value, LookIn:=xlValues, Lookat:=xlWhole, MatchCase:=False) '<--| always specify those 4 Find() method parameters
            If FoundCell Is Nothing Then
               .Cells(origValue, 1).Value = Sheets("Cases").Cells(origValue, 1).Value
            Else
            End If
        Next
    End With
End Sub

Find()方法的评论是由于它的任何使用(甚至来自Excel UI)将这些参数设置为默认值以供后续使用。因此,最好始终指定每次实际需要的内容。

最后应该没有Else子句来处理,然后代码可以崩溃

Public Sub main2()
    Dim maxVal As Long
    Dim origValue As Long

    With Worksheets("Complications") '<--| reference this sheet once and for all and rest assure you're dealing with it if not otherwise explicitly referenced
        maxVal = .Range(.Rows.Count, 1).End(xlUp).Row '<--| find the "real" last non blank cell in column A, should any blank cell precede it
        For origValue = 2 To maxVal
            If .Range("A1", "A50000").Find(What:=.Cells(origValue, 1).Value, LookIn:=xlValues, Lookat:=xlWhole, MatchCase:=False) Is Nothing Then .Offset(origValue - 1).Value = Sheets("Cases").Cells(origValue, 1).Value '<--| always specify those 4 parameters of Find() method
        Next
    End With
End Sub