首页 > 解决方案 > 访问另一个库中工作簿的数据

问题描述

我想访问另一个目录中的工作簿中的数据,但我不知道语法,你能帮我吗?

我尝试过类似的方法,但它不起作用

Workbooks("U:\a.xlsx").Sheets("a").Range("A2")

标签: excelvba

解决方案


要读取一个值,您需要先打开该文件。

Dim MyWb As Workbook
Set MyWb = Workbooks.Open(Filename:="U:\a.xlsx", ReadOnly:=True) 'readonly if you only need to read

'read the value
Debug.Print MyWb.Worksheets("a").Range("A2")

'close it after reading
MyWb.Close SaveChanges:=False

或者,如果您想在不显示工作簿的情况下将其隐藏在后台:

'open a new hidden Excel
Dim ExApp As Excel.Application
Set ExApp = New Excel.Application 
ExApp.Visible = False

'open the workbook in that hidden ExApp
Dim MyWb As Workbook
Set MyWb = ExApp.Workbooks.Open(Filename:="U:\a.xlsx", ReadOnly:=True)

'read the value
Debug.Print MyWb.Worksheets("a").Range("A2")

'close it after reading
MyWb.Close SaveChanges:=False

'close hidden Excel
ExApp.Quit

此处适当的错误处理可能有助于确保在出现任何错误时关闭 ExApp。否则,该过程将保持打开状态。


推荐阅读