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

Paste_Image.png
- 如上圖,用Vlookup函數(shù)查詢另一個工作簿的數(shù)據(jù),要想公式能夠有效,需要同時打開2個工作簿。
- 因此,使用VBA代替上面的Vlookup函數(shù)查詢,其道理一樣。
- 1、打開查詢的數(shù)據(jù)所在的工作簿(指定的)。
- 2、用代碼獲取需要的數(shù)據(jù),實現(xiàn)目的。
- 3、關閉數(shù)據(jù)工作簿(不保存更改)。
- 4、以上步驟使用VBA操作來代替人工。
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
'第一部分:打開工作簿
Set Sht = ThisWorkbook.Sheets("查詢表") '數(shù)據(jù)查詢表
Set wkb_data = Workbooks.Open(fullpath) '打開數(shù)據(jù)所在的工作簿
'第二部分:vba代碼操作,獲取目標數(shù)據(jù)
With Sheets("數(shù)據(jù)表")
For i = 2 To Sht.Cells(Rows.Count, 1).End(xlUp).Row '遍歷查詢表要查詢數(shù)據(jù)的部門
For j = 2 To .Cells(Rows.Count, 1).End(xlUp).Row '遍歷數(shù)據(jù)
If Sht.Cells(i, 1) = .Cells(j, 1) Then '按部門查詢
Sht.Cells(i, 2) = .Cells(j, 2) '輸出銷售額
Exit For '有結果就退出當前循環(huán),不再繼續(xù)遍歷下去
End If
Next
Next
End With
'第三部分:關閉工作簿
wkb_data.Close False '關閉工作簿,不保存更改
Set wkb_data = Nothing '釋放對象變量
Application.ScreenUpdating = True
End Sub
-
得出結果:
Paste_Image.png
