简体   繁体   中英

VBA vlookup using Excel reference table in external workbook

Right now, I'm using this type of code to look at what's in column O to determine what to enter in column N. Since the data is confidential, I'm just making it letters and numbers here. It works fine, but instead of hardcoding the cases in the VBA code, I want it to reference a table that is in an external workbook because I'm going to have thousands of cases and values to insert.

Sub ChangeTest()
    Dim LastRow As Long
    Dim i As Long
      LastRow = Range("O" & Rows.Count).End(xlUp).Row
      For i = 2 To LastRow
        Select Case Range("O" & i)
          Case "A", "B", "C"
            Range("N" & i) = "1"
          Case "D","E","F"
            Range("N" & i) = "2"
          Case "G","H","I"
            Range("N" & i) = "3"
        End Select
      Next i
End Sub

In the external workbook, column D will contain the cases (A, B, C, etc.) and column C will have the number (1, 2, 3, etc.) that is to go into column N in the original workbook.

I'm not sure if the code I have now needs to be edited slightly to incorporate the reference table or if it's going to need to be completely different.

Why not just run a vlookup like you title suggests instead of running a loop?:

Sub ChangeTest()
Dim LastRow As Long
Dim Referance_Workbook As Workbook
Dim Referance_Tab As Worksheet
Dim Rng As Range


Set Referance_Workbook = Workbooks.Open("[Referance workbook path]")
Set Referance_Tab = Referance_Workbook.Sheets("[Referance tab within referance workbook]")
Referance_Workbook.Close SaveChanges:=False

LastRow = Range("O" & Rows.Count).End(xlUp).Row
Set Rng = Range("N2:N" & LastRow)
Rng.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-11],'[Source Workbook.xlsx]Sheet1'!C1:C2,2,0),""No in refrence table"")"


End Sub

This does a lookup on column A of you reference workbook/tab and looks for a result in column B

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