简体   繁体   中英

excel VBA runtime error - 1004

I'm just trying to do something very simple with Vlookup, but am getting the 1004 error. Would really, really appreciate your help. Thanks in advance. Here's my code:

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

When you use VLOOKUP as a member of WorksheetFunction, an error will result in a runtime error. When you use VLOOKUP as a member of Application, an error will result in a return value that's an error, which may or may not result in a runtime error. I have no idea why MS set it up this way.

If you use WorksheetFunction, you should trap the error. If you use Application, you should use a Variant variable and test for IsError. Here are a couple of examples.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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