如何把这个基于macros的function变成一个真正的VBAfunction?

我正在尝试编写VBA函数,以便可以访问已closures的Excel工作簿的单元格值。 我在网上发现,可以这样写一个macros程序:

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()作为macros,但是当我尝试直接在Excel单元格中使用GetValue(…)作为自定义VBA函数时,它不起作用。 看来,这一行

  GetValue = ExecuteExcel4Macro(arg) 

不能执行。

有谁知道如何解决这个问题? 我正在使用Excel 2010。

据我所见,ExecuteExcel4Macro函数没有定义。 但是可能有更简单的方法。 尝试打开包含desierd值的工作簿。 例如

 tempWb as workbook dim testValue set tempWb = application.workbooks.open(path) testValue = tempWb.sheets(1).cells(1,1) 

path可以像你的例子那样传递。