我正在处理工作簿"file"。然后,我打开另一个工作簿(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 以在其他文档中使用它,但不幸的是它不起作用。有人可以帮忙吗?
最佳答案
您处理工作簿就像处理工作簿中的工作表一样。指定外部工作簿很重要,但您要从中检索信息的外部工作簿中的工作表也很重要。
幸运的是,Range.Address property可以通过指定可选的外部参数来处理很多事情。
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
有很多缺失的信息,但如果您正确分配了所有变量,这应该是一个很好的入门框架。
关于VBA vlookup 具有定义的范围和其他工作簿中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32148792/