2015-09-22 92 views
0

我使用2個工作簿運行一個簡單的VLOOKUP。這歷來被手工完成,但現在我需要的過程自動化每月:使用通配符查找文件excel

我通常使用類似,

= VLOOKUP(D1,「[PD1_Book1_15-09-22.xls]直播」! $ A:$ A,1,0)..在當前工作簿稱爲NW 01-09,工作表名稱「主」,單元格F1。然後我將整個功能複製到列中。最終的結果是很多#N/A,我立即過濾出來。

的問題是這兩個工作簿定期更改其名稱(例如..「PD * 第一冊- - 的.xls,在這種情況下, 「第一冊」 是恆定的,NW ** -,在這種情況下,NW爲常數)

與「活」片活躍「PD _Book1_的.xls」我已經試過這

如此,但不能讓它在所有的工作。

Sub Lookup() 
myFileName = ActiveWorkbook.Name 
mySheetName = ActiveSheet.Name 
myRangeName = Range("A:A") 

Dim wb As Workbook 
For Each wb In Workbooks 
If wb.Name Like "NW*.*" Then 
wb.Activate 
Exit Sub 
End If 
Next 

Range("F1").Formula = "=VLOOKUP(A1,[" & myFileName & "]" & mySheetName & "!" & myRangeName & ",1,0)" 

End Sub 

我完全失去這一個,任何幫助 會很好。如果我不能在1個單元上工作,我不知道如何填充它們全部!

在我們到達此點之前,NW工作簿將始終打開,因爲它受到通過宏清除數據的負載的影響。我很高興爲PD * Book1 **。如果它更容易打開xls。用於查詢的數據在工作表上「Live」

我是vba的新手,並且認爲我咬過的東西比我咀嚼的更多。提前致謝。

回答

0

試試這個:

Sub wcard() 

Dim k As Workbook 'looper 
Dim wbs As Workbook 'source of the data 
Dim wbt As Workbook 'target of the data 
Dim ws As Worksheet 'source of the data 
Dim wt As Worksheet 'target of the data 
Dim i As Long 'just a counter 
Dim lrow As Long 'variable for the lastrow formula 
Dim wnm As String 'helps with the formula 


For Each k In Workbooks 'loop through the open workbooks and 
'assign the source and target variables to the correct workbooks 

    If k.Name Like "NW*.*" Then 

     Set wbt = k 

    Else 

     If k.Name Like "PD*Book1*.*" Then 

      Set wbs = k 
     End If 

    End If 

Next k 'end of our loop 

Set ws = wbs.Sheets("Live") 'assign sheets 
Set wt = wbt.Sheets("Master") 'assign sheets 

wnm = wbs.Name 


lrow = wt.Range("A" & Rows.Count).End(xlUp).Row 
'find the last rows in your master file that has entries 
'(substitute "A" for the column by which you would determine that) 

For i = 1 To lrow Step 1 'loop through the rows of your master to put the 
'formula in each of them 

    wt.Range("F" & i).Formula = "=VLOOKUP(A" & i & ",[" & wnm & "]Live'!$A:$A,1,0)" 
    ' your formula - note that your sheet name and the range for the lookup do not change 
    'depending on the workbook, so no need to put them as variables 

Next i 

End Sub 
+0

哇!我可以跟隨它。只是。雖然我得到了一個運行時91對象變量,但未在「wbt = k」處設置錯誤。我查看了幫助文件,但我不清楚它。 – Gabbana

+0

@Gabbana對不起,忘了放'set' - 可能不好,原帖已修改並修復 –

+0

不用擔心。我解決了它。工作很棒! – Gabbana