2015-08-21 43 views
2

我正在工作簿「文件」。然後,我打開另一個用於查找數據的工作簿(Masterfile)。VBA查找與定義的範圍和從其他工作簿中的文件

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

我猜這是你的代碼的一部分,因爲只是做一個表單上的查找?如果是這樣,請嘗試使用find。此外,限定您的範圍。 – findwindow

回答

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,WorksheetRange對象變量的指南。

+0

'ReferenceStyle:= xlR1C1'上面有很好的結果,我偷了這個以加入我的回覆。:P – Jeeped

+0

@ChipLetten:thx,I沒有考慮R1C1表示法,我會查看你提到的指南!-) – Johannes

+0

@Jeeped的答案顯示瞭如何使用對象變量。 – ChipsLetten

0

不能確定是否有在你發佈什麼錯別字,或者如果你直接從你的代碼粘貼複製BU有錯誤應該是這樣的:

Range("K2").FormulaR1C1 = "=VLOOKUP(RC[-1],'" & Masterfile.Name & "'!" & SelectionMasterfile & ",1, FALSE)" 
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 

有很多缺少的信息,但如果你得到所有的賦值正確指定,這應該是一個很好的框架開始。

+0

非常感謝併發布信息不足。 我把你的代碼與 = VLOOKUP(RC [-2],「&SelectionMasterfile&」,1,FALSE)「 這給了我exactely我所需要的! – Johannes

+0

記得給ChipsLetten功勞, ReferenceStyle:= xlR1C1'和我的'external:= True'似乎是解決方案。 – Jeeped

相關問題