- 跨工作簿讀取數(shù)據(jù)可以按以下思路來(lái)操作:

Paste_Image.png
- 如上圖,用Vlookup函數(shù)查詢另一個(gè)工作簿的數(shù)據(jù),要想公式能夠有效,需要同時(shí)打開(kāi)2個(gè)工作簿。
- 因此,使用VBA代替上面的Vlookup函數(shù)查詢,其道理一樣。
- 1、打開(kāi)查詢的數(shù)據(jù)所在的工作簿(指定的)。
- 2、用代碼獲取需要的數(shù)據(jù),實(shí)現(xiàn)目的。
- 3、關(guān)閉數(shù)據(jù)工作簿(不保存更改)。
- 4、以上步驟使用VBA操作來(lái)代替人工。
Sub 跨工作簿查詢()
Dim Sht As Worksheet '查詢工作表
Dim wkb_data As Workbook '數(shù)據(jù)工作簿
Dim fullpath As String '路徑帶工作簿名稱
Dim i As Long
fullpath = ThisWorkbook.Path & "\小狗.xlsx"
Application.ScreenUpdating = False
'第一部分:打開(kāi)工作簿
Set Sht = ThisWorkbook.Sheets("查詢表") '數(shù)據(jù)查詢表
Set wkb_data = Workbooks.Open(fullpath) '打開(kāi)數(shù)據(jù)所在的工作簿
'第二部分:vba代碼操作,獲取目標(biāo)數(shù)據(jù)
With Sheets("數(shù)據(jù)表")
For i = 2 To Sht.Cells(Rows.Count, 1).End(xlUp).Row '遍歷查詢表要查詢數(shù)據(jù)的部門(mén)
For j = 2 To .Cells(Rows.Count, 1).End(xlUp).Row '遍歷數(shù)據(jù)
If Sht.Cells(i, 1) = .Cells(j, 1) Then '按部門(mén)查詢
Sht.Cells(i, 2) = .Cells(j, 2) '輸出銷(xiāo)售額
Exit For '有結(jié)果就退出當(dāng)前循環(huán),不再繼續(xù)遍歷下去
End If
Next
Next
End With
'第三部分:關(guān)閉工作簿
wkb_data.Close False '關(guān)閉工作簿,不保存更改
Set wkb_data = Nothing '釋放對(duì)象變量
Application.ScreenUpdating = True
End Sub
-
得出結(jié)果:
Paste_Image.png
