VBA vlookup与其他工作簿定义的范围和文件

我在工作簿“文件”中工作。 然后,我打开另一个用于查找数据的工作簿(Masterfile)。

Workbooks.Open FileName:=Path & Masterfile lRowMasterfile = Cells(Rows.Count, "A").End(xlUp).Row SelectionMasterfile = Range("A1").CurrentRegion.Address Workbooks(File).Activate Range("K2").FormulaR1C1 = "=VLOOKUP(RC[-1],'" & Masterfile"' & ! & SelectionMasterfile,1, FALSE)" Range("K2").AutoFill Destination:=Range("K2:K" & lRowFile) Workbooks(Masterfile).Close 

我定义了Masterfile和Range来在其他文档中使用它,但不幸的是它不起作用。 任何人都可以帮忙吗?

你有两个问题。

这一行给你一个A1符号的地址(例如$ A $ 1:$ B $ 3):

 SelectionMasterfile = Range("A1").CurrentRegion.Address 

但是您正在使用R1C1表示法(例如R1C1:R3C2)构build公式,并且您缺less工作表名称。 尝试这个:

 SelectionMasterfile = ActiveSheet.Name & "!" & Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1) 

另一个问题是你有语音标记的地方有错误。

 Range("K2").FormulaR1C1 = "=VLOOKUP(RC[-1],'[" & Masterfile & "]'" & SelectionMasterfile & ",1, FALSE)" 

PS您应该始终尝试完全限定纸张和范围。 查找使用WorkbookWorksheetRange对象variables的指南。

您正在处理工作簿,就像他们是工作簿中的工作表一样。 指定外部工作簿很重要,但是您正在从中检索信息的外部工作簿中的工作表也是如此。

值得庆幸的是,通过指定可选的外部参数, Range.Address属性可以处理很多这种情况。

 Dim mwb As Workbook Dim lRowMasterfile As Long, lRowFile As Long, SelectionMasterfile As String Dim Path As String, Masterfile As String, File As String Path = ThisWorkbook.Path '<~~ set this properly! Masterfile = "MasterWorkbook.xlsx" '<~~ set this properly! File = ActiveWorkbook.Name '<~~ set this properly! Set mwb = Workbooks.Open(Filename:=Path & Masterfile) With mwb With .Worksheets("Sheet1") '<~~ what worksheet are you trying to get information from?!? lRowMasterfile = .Cells(Rows.Count, "A").End(xlUp).Row SelectionMasterfile = .Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1, external:=True) End With End With With Workbooks(File) With .Worksheets("Sheet1") '<~~ what worksheet are you trying to put information into?!? lRowFile = 0 '<~~ set this properly! 'this VLOOKUP only checks to see if the value exists, it doesn't lookup anything but the first column 'in any event, you can put them all in at the saame time .Range("K2:K" & lRowFile).FormulaR1C1 = _ "=VLOOKUP(RC[-1], " & SelectionMasterfile & ", 1, FALSE)" End With End With mwb.Close False Set mwb = Nothing 

有很多遗漏的信息,但是如果你正确地分配了所有的variables,这应该是一个很好的开始的框架。

不知道是否在你发布的内容中有拼写错误,或者如果你直接从你的代码中粘贴了一个副本,有错误它应该看起来像这样:

 Range("K2").FormulaR1C1 = "=VLOOKUP(RC[-1],'" & Masterfile.Name & "'!" & SelectionMasterfile & ",1, FALSE)"