应用程序定义的错误或对象错误

任何人都可以看看我的代码,并帮我找出我做错了什么? 提前致谢!

Sub Price() Dim ilastrow As Long Dim i As Long ilastrow = Sheets(2).Cells(Rows.Count, 4).End(xlUp).Row For i = ilastrow To 2 Step -1 Sheets(2).Cells(i, 10).Value = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(Sheets(2).Cells(i, 4).Value, Sheets(1).Range("D2:F520"), 2, False), 0) Sheets(2).Cells(i, 11).Value = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(Sheets(2).Cells(i, 4).Value, Sheets(1).Range("D2:F520"), 3, False), 0) Next i End Sub 

如果您使用一些variables,您的代码将更容易维护和阅读。

此外,您可以删除WorksheetFunction并使用IsError()testing返回值

 Sub Price() Dim ilastrow As Long Dim i As Long, v, res, rng As Range ilastrow = Sheets(2).Cells(Rows.Count, 4).End(xlUp).Row Set rng = Sheets(1).Range("D2:F520") For i = ilastrow To 2 Step -1 With Sheets(2).Rows(i) v = .Cells(4).Value res = Application.VLookup(v, rng, 2, False) .Cells(10).Value = IIf(IsError(res), 0, res) res = Application.VLookup(v, rng, 3, False) .Cells(11).Value = IIf(IsError(res), 0, res) End With Next i End Sub 

尝试使用评估方法,例如:

 Sheets(2).Cells(i, 10).Value = Evaluate("=IFERROR(VLOOKUP(D" & i & ",'" & Sheets(1).Name & "'!$D$2:$F$520,2,FALSE),0)") 

另外,你确定表单(1)是否正确? 如果您已经添加/删除工作表,那么索引可能会发生变化,并且工作表可能不再存在。 在可能的情况下,应该引用图纸名称或将工作表设置为variables,然后使用该variables。

例如:

 Dim ws1 As Worksheet, ws2 As Worksheet Set ws1 = Sheets("This Sheet") Set ws2 = Sheets("That Sheet") ws1.Cells(i, 10).Value = Evaluate("=IFERROR(VLOOKUP(D" & i & ",'" & ws2.Name & "'!$D$2:$F$520,2,FALSE),0)") 

在VBA中不能使用工作表函数IFERROR作为Application.IfError 。 捕获错误足以在以这种方式使用时抛出错误。 这是一个非破坏性的方法,在使用VLOOKUP检索值之前检查VLOOKUP是否匹配。

 Sub Price() Dim ilastrow As Long, i As Long With Sheets(2) ilastrow = .Cells(Rows.Count, 4).End(xlUp).Row For i = ilastrow To 2 Step -1 .Cells(i, 10).Resize(1, 2) = 0 If CBool(Application.CountIf(Sheets(1).Columns("D"), .Cells(i, 4).Value)) Then .Cells(i, 10).Value = Application.VLookup(.Cells(i, 4).Value, Sheets(1).Range("D2:F520"), 2, False) .Cells(i, 11).Value = Application.VLookup(.Cells(i, 4).Value, Sheets(1).Range("D2:F520"), 3, False) 'alternate method '.Cells(i, 10).Resize(1, 2) = Sheets(1).Cells(Application.Match(.Cells(i, 4).Value, Sheets(1).Range("D2:D520"), 0) + 1, 5).Resize(1, 2).Value End If Next i End With End Sub