我是 VBA 新手,我正在尝试编写一个可以从 Excel 单元格调用的函数,该函数可以打开一个已关闭的工作簿,查找一个单元格值并返回它。
到目前为止,我知道如何编写这样的宏:
Sub OpenWorkbook()
Dim path As String
path = "C:\Users\UserName\Desktop\TestSample.xlsx"
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
currentWb.Sheets("Sheet1").Range("A1") = OpenWorkbookToPullData(path, "B2")
End Sub
Function OpenWorkbookToPullData(path, cell)
Dim openWb As Workbook
Set openWb = Workbooks.Open(path, , True)
Dim openWs As Worksheet
Set openWs = openWb.Sheets("Sheet1")
OpenWorkbookToPullData = openWs.Range(cell)
openWb.Close (False)
End Function
宏 OpenWorkbook() 运行得非常好,但是当我尝试直接从 Excel 单元格调用 OpenWorkbookToPullData(...) 时,它不起作用。该声明:
Set openWb = Workbooks.Open(path, , True)
什么都不返回。
有谁知道如何将它变成可以从 Excel 单元格调用的有效 VBA 函数?