我正在尝试编写代码以使用vlookup
,其中引用是另一个文件。参考表从单元格a2
到a300
。查找值是从单元格G2
到列尾。 vlookup
将在列AA
中完成。
我在此网站上的一种解决方案中找到以下代码,但不知道如何更改它以适合我的文件。
Sub SBEPlannerAdder()
Dim rw As Long, x As Range
Dim extwbk As Workbook, twb As Workbook
Set twb = Workbooks.Open("C:\Users\OUROBOROS\Desktop\30-5-19\vba\VBA\Gents_SW_May'19.xlsb")
Set extwbk = Workbooks.Open("C:\Users\OUROBOROS\Desktop\30-5-19\vba\VBA\1st phase stores.xlsx")
Set x = extwbk.Worksheets("Sheet1").Range("A1:C300")
For rw = 2 To twb.Sheets("Sheet1").Cells(Rows.Count, 25).End(xlUp).Row
twb.Sheets("Sheet1").Cells(rw, 2) = Application.VLookup(twb.Sheets("Sheet1").Cells(rw, 1).Value2, x, 2, False)
Next rw
extwbk.Close savechanges:=False
End Sub
答案 0 :(得分:0)
尝试一下。您需要调整工作簿和工作表的名称以适应需要。
不确定您期望的输出是什么,我刚刚在AA的输出单元格中添加了一条短信。
Sub y()
Dim rw As Long, x As Range, v As Variant
Dim extwbk As Workbook, twb As Workbook
Set twb = ThisWorkbook 'file with lookup values (containing code)
Set extwbk = Workbooks.Open("C:\Users\OUROBOROS\Desktop\30-5-19\vba\VBA\1st phase stores.xlsx") 'file with reference table
Set x = extwbk.Worksheets("Sheet1").Range("A2:A300")
For rw = 2 To twb.Sheets("Sheet1").Cells(Rows.Count, "G").End(xlUp).Row
v = Application.Match(twb.Sheets("Sheet1").Cells(rw, "G").Value2, x, 0)
If IsNumeric(v) Then
twb.Sheets("Sheet1").Cells(rw, "AA").Value = "Found" 'G is in the table
Else
twb.Sheets("Sheet1").Cells(rw, "AA").Value = "Not found" ''G is NOT in the table
End If
Next rw
extwbk.Close savechanges:=False
End Sub