简体   繁体   中英

VBA IF Then Vlookup Multiple Sheet

I am trying to retrieve data from another file using the VLOOKUP function however this is only to happen depending on if any of the 2 items of data appear in column 3(C)

"PO Materials" OR "PO Labor"

Sub MakeFormulas()

Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Dim X As Long

'What are the names of our worksheets?
Set sourceSheet = Worksheets("Sheet1")
Set outputSheet = Worksheets("Sheet2")


'Determine last row of source
With sourceSheet
    SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

With outputSheet

    'Determine last row in col C
    OutputLastRow = .Cells(.Rows.Count, "E").End(xlUp).Row

    For X = 5 To OutputLastRow
        If InStr(1, .Range("C" & X), "PO Materials") > 0 Then
            'Apply our formula
        .Range("Q2:Q" & OutputLastRow).Formula = _
            "=VLOOKUP(E2,'" & sourceSheet.Name & "'!$A$2:$B$" & SourceLastRow & ",2,0)"
        End If
    Next
End With

End Sub

Code is working; However, its giving #N/A if the cell is blank or contains any value in Column C, which means its not recognizing the If statement. If the column does not containn "PO Materials" or "PO Labor" I would like it to skip to the next cell in the range

Thanks in advance for any help given.

The code that generates the VLOOKUP is applying that formula to each cell in the column every time. That is, every time your If condition finds "PO Materials", it will apply the VLOOUKP to every cell between Q2 and the last row from column E.

I think this is what you want:

.Range("Q" & X).Formula = _
    "=VLOOKUP(E" & X & ",'" & sourceSheet.Name & "'!$A$2:$B$" & SourceLastRow & ",2,0)"

Alternatively, it could be done completely within the spreadsheet:

=IF(ISERROR(FIND("PO Materials",C6)),"",VLOOKUP(E6,Sheet1!$A$2:$B$6,2,0))

Final Code for future reference

Sub MakeFormulas()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Dim X As Long

'What are the names of our worksheets?
Set sourceSheet = Worksheets("Sheet1")
Set outputSheet = Worksheets("Sheet2")


'Determine last row of source
With sourceSheet
SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet

'Determine last row in col C
OutputLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row

For X = 2 To OutputLastRow
If InStr(1, .Range("C" & X), "PO Materials") + InStr(1, .Range("C" & X), "PO Labor") > 0 Then
    'Apply our formula
.Range("Q" & X).Formula = _
"=VLOOKUP(E" & X & ",'" & sourceSheet.Name & "'!$A$2:$B$" & SourceLastRow & ",2,0)"
End If
Next
End With
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