我正在使用工作簿“文件”。然后,我打开另一个用于查找数据的工作簿(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以在其他文档中使用它,但遗憾的是它不起作用。有人可以帮忙吗?
答案 0 :(得分:2)
您正在处理工作簿,就像它们是工作簿中的工作表一样。指定外部工作簿很重要,但是要从中检索信息的外部工作簿中的工作表也是如此。
值得庆幸的是,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
有很多缺少的信息,但是如果你正确分配了所有的变量,这应该是一个很好的入门框架。
答案 1 :(得分:1)
你有两个问题。
此行以A1表示法为您提供地址(例如$ A $ 1:$ B $ 3):
SelectionMasterfile = Range("A1").CurrentRegion.Address
但是您使用R1C1表示法构建公式(例如R1C1:R3C2)并且您缺少工作表名称。试试这个:
SelectionMasterfile = ActiveSheet.Name & "!" & Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1)
另一个问题是你的语音标记出现了错误。
Range("K2").FormulaR1C1 = "=VLOOKUP(RC[-1],'[" & Masterfile & "]'" & SelectionMasterfile & ",1, FALSE)"
PS您应该始终尝试完全限定工作表和范围。查找使用Workbook
,Worksheet
和Range
对象变量的指南。
答案 2 :(得分:0)
不确定您发布的内容是否存在拼写错误,或者您是否直接从代码中粘贴了副本有错误它应该如下所示:
Range("K2").FormulaR1C1 = "=VLOOKUP(RC[-1],'" & Masterfile.Name & "'!" & SelectionMasterfile & ",1, FALSE)"