繁体   English   中英

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

[英]Excel VBA Find Function getting runtime Error 1004

每次尝试运行此代码时,都会出现以下错误:“运行时错误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

任何帮助将非常感激!

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

您输入的范围不正确。

作为布鲁斯·韦恩(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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM