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

每次我尝试运行这个代码时,我得到这个错误:'运行时错误1004:应用程序定义或对象定义的错误'它具体不喜欢“查找”function,没有它,它运行良好。

我的代码如下所示:

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)

你只是input了错误的范围。

作为布鲁斯·韦恩是你的问题的答案,以下可能会帮助你避免将来可能出现的问题:

 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用户界面)都将这些参数设置为默认值以供后续使用。 所以最好总是指定你每次需要的东西。

最后应该没有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