0

我只是想用 Vlookup 做一些非常简单的事情,但我得到了 1004 错误。真的非常感谢您的帮助。提前致谢。这是我的代码:

Sub test()
    Dim user As String
    Dim drawn As String
    Set Sheet = ActiveWorkbook.Sheets("consolidated")

    For i = 2 To 2092
        user = CStr(Cells(i, 1).Value)
        Set Sheet = ActiveWorkbook.Sheets("sections")
        drawn = CStr(Application.WorksheetFunction.VLookup(user, Sheet.Range("A2:B3865"), 2))
        Set Sheet = ActiveWorkbook.Sheets("consolidated")
        Cells(i, 10).Value = drawn
    Next i
End Sub
4

1 回答 1

3

当您使用 VLOOKUP 作为 WorksheetFunction 的成员时,错误将导致运行时错误。当您使用 VLOOKUP 作为 Application 的成员时,错误将导致返回值是错误,这可能会或可能不会导致运行时错误。我不知道为什么 MS 以这种方式设置它。

如果您使用 WorksheetFunction,您应该捕获错误。如果您使用 Application,您应该使用 Variant 变量并测试 IsError。这里有几个例子。

Sub VlookupWF()

    Dim sUser As String
    Dim sDrawn As String
    Dim shSec As Worksheet
    Dim shCon As Worksheet
    Dim i As Long

    Set shSec = ActiveWorkbook.Worksheets("sections")
    Set shCon = ActiveWorkbook.Worksheets("consolidated")

    For i = 2 To 2092
        sUser = shCon.Cells(i, 1).Value
        'initialize sDrawn
        sDrawn = vbNullString

        'trap the error when using worksheetfunction
        On Error Resume Next
            sDrawn = Application.WorksheetFunction.VLookup(sUser, shSec.Range("A2:B3865"), 2, False)
        On Error GoTo 0

        'see if sdrawn is still the initialized value
        If Len(sDrawn) = 0 Then
            sDrawn = "Not Found"
        End If

        shCon.Cells(i, 10).Value = sDrawn
    Next i

End Sub

Sub VlookupApp()

    Dim sUser As String
    Dim vDrawn As Variant 'this can be a String or an Error
    Dim shSec As Worksheet
    Dim shCon As Worksheet
    Dim i As Long

    Set shSec = ActiveWorkbook.Worksheets("sections")
    Set shCon = ActiveWorkbook.Worksheets("consolidated")

    For i = 2 To 2092
        sUser = shCon.Cells(i, 1).Value
        vDrawn = Application.VLookup(sUser, shSec.Range("A2:B3865"), 2, False)

        'see if vDrawn is an error
        If IsError(vDrawn) Then
            vDrawn = "Not Found"
        End If

        shCon.Cells(i, 10).Value = vDrawn
    Next i

End Sub
于 2013-08-06T16:01:48.740 回答