简体   繁体   中英

Excel VBA: How to create VLOOKUP with unique range and multiple worksheets?

I am still new to vba and currently trying to write a code in which it performs a vlookup from my source sheet and output sheet and put it in my output sheet. I need the vlookup to be performed for the entire column A (which varies in number of rows each month) and placed in column G. Whenever I try to run it, it says "Error 438: Object doesn't support this property or method." I found this code somewhere online, and tried to change it to match my data. I'm guessing my sourceSheet isn't assigned to the sheet, even though I specified it? Can anyone help:

Here is my code:

Sub Vlookup()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Set sourceSheet = Worksheets("Data1")
Set outputSheet = Worksheets("Info2")
With sourceSheet
     SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet
    OutputLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
  'This is the line where I keep getting the error:
 .Range("G2:G" & OutputLastRow).Formula = _
             "=VLOOKUP(A2,'" & sourceSheet & "'!$A$2:$B$" & SourceLastRow & ",2,0)"
    End With
    End Sub

You're referring to the sheet itself, not it's name. Try:

.Range("G2:G" & OutputLastRow).Formula = _
         "=VLOOKUP(A2,'" & sourceSheet.Name & "'!$A$2:$B$" & SourceLastRow & ",2,0)"

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