简体   繁体   English

在外部工作簿中使用Excel参考表的VBA vlookup

[英]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. 现在,我正在使用这种类型的代码来查看O列中的内容,以确定在N列中输入的内容。由于数据是机密信息,因此我只是在此处使用字母和数字。 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. 它可以正常工作,但是我希望它引用外部工作簿中的表,而不是用VBA代码对情况进行硬编码,因为我要插入成千上万的情况和值。

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. 在外部工作簿中,D列将包含个案(A,B,C等),而C列将具有要在原始工作簿的N列中输入的数字(1、2、3等)。

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?: 为什么不运行像您标题所示的vlookup而不是运行循环?

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 这会在您参考工作簿/标签的A列上进行查找,并在B列中查找结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM