简体   繁体   中英

VBA: Why can't I use two VLookUps in a row?

I am trying to use two VLookUps in a row in my macro. The macro counts the IDs in column A and C, searches for the ID description in another table (same sheet and ranges from column F to M -> F = IDs, H = ID description) and continues this search until the count is reached and inserts them in column B and D.

Unfortunately, I get a

run time error 1004

when using the second VLookUp. First one works fine and it's exactly the same as in the first one I am just referring to different cells.

Picture reference of what I am trying to achieve:

在此输入图像描述

Does anyone know what causes this problem?

Dim i As Integer
Dim shA As Worksheet
Set shA = Worksheets(Format(Date, "dd.mm.yyyy"))
With shA

 For i = 4 To .Range("A4", .Range("A4").End(xlDown)).Rows.Count + 3
        .Cells(i, 2) = .Application.WorksheetFunction.VLookup(.Cells(i, 1), .Range("F:M"), 3, False)
 Next i 

 For i = 4 To .Range("C4", .Range("C4").End(xlDown)).Rows.Count + 3
        .Cells(i, 4) = .Application.WorksheetFunction.VLookup(.Cells(i, 3), .Range("F:M"), 3, False)
 Next i

End With

Try to replace Integer with Long and try again. In VBA Integer is

from -2^15 to 2^15-1 or

from -32768 to 32767

Thus, if you use it in Excel and it refers numbers which are outside this range, you get an error. In general, you have some other errors as well. Try this and make sure that you have the correct ActiveSheet selected (I have done it for easy, you may change it later):

Public Sub TestMe()

    Dim i As Long

    Dim shA As Worksheet
    Set shA = ActiveSheet

    With shA
        For i = 4 To .Range("A4", .Range("A4").End(xlDown)).Rows.Count + 3
            .Cells(i, 2) = Application.VLookup(.Cells(i, 1), .Range("F:M"), 3, False)
        Next i
        For i = 4 To .Range("C4", .Range("C4").End(xlDown)).Rows.Count + 3
            .Cells(i, 4) = Application.VLookup(.Cells(i, 3), .Range("F:M"), 3, False)
        Next i
    End With
End Sub

Thus, in general:

  • Do not use On Error Resume Next , because it is a bit tough.
  • When you use With Worksheets("someName") , then make sure that every time you put a dot . , the child is a real child of the with-Parent . In your case .Application is not a child of Worksheets()
  • Do not use Integer , but Long

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