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

时间:2014-11-26 21:33:40

标签: excel vba vlookup

任何人都可以查看我的代码并帮我找出哪些错误?提前谢谢!

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

3 个答案:

答案 0 :(得分:1)

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

此外,您可以删除WorksheetFunction并使用IsError()

测试返回值
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

答案 1 :(得分:0)

请尝试使用evaluate方法,例如:

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

另外,你确定Sheets(1)是正确的表吗?如果您一直在添加/删除工作表,则索引可能会发生更改,并且该工作表可能不再存在。在可能的情况下,您应该引用工作表名称或将工作表设置为变量并改为使用它。

例如:

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)")

答案 2 :(得分:0)

您无法在VBA中将工作表函数IFERROR用作Application.IfError。捕获错误足以在以这种方式使用时抛出错误。这是一种非破坏性的方法,可以在使用它来检索值之前检查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