【发布时间】:2013-10-29 05:09:28
【问题描述】:
我正在尝试编写一个 VBA 函数,以便我可以访问已关闭的 Excel 工作簿的单元格值。我在网上发现可以写一个这样的宏例程:
Public Sub TestGetValue()
p = "C:\Users\Jake\Desktop"
f = "TestSample.xlsx"
s = "Sheet1"
a = "B10"
Call GetValue(p, f, s, a)
x = GetValue(p, f, s, a)
MsgBox x
End Sub
Public Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
range(ref).range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
我可以将TestGetValue() 作为宏运行,但是当我尝试在 Excel 单元格中直接使用GetValue() 作为自定义 VBA 函数时,它不起作用。 GetValue = ExecuteExcel4Macro(arg)这行好像不能执行。
有谁知道如何解决这个问题?我正在使用 Excel 2010。
【问题讨论】:
-
见this
-
还有this 所以回答
-
谢谢,但仍然......我知道如何编写一个可以打开工作簿和更新数据的宏,但我不知道如何编写可以从 Excel 单元格调用的 VBA 函数。例如,如果您编写这样的函数:
codeFunction OpenWorkbookToPullData(path, cell) Dim openWb As Workbook Set openWb = Workbooks.Open(path) Dim openWs As Worksheet Set openWs = openWb.Sheets("Sheet1") OpenWorkbookToPullData = openWs.Range(cell) openWb.Close (False) End Functioncode你不能从 Excel 单元格调用这个函数,虽然你可以从宏调用它。 -
这超出了函数的范围。函数可以返回值,但无法像您希望的那样作用于环境。即使你能做到这一点,我也不认为这将是一个好的选择,因为会发生大量的资源计算。根据需要编写代码以将值转储到单元格中可能会更好。