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 に答える