这是我在单元格中使用的函数的简化版本(例如= xxDay(B7))从已关闭的工作簿中检索一天:
Function xxDay(row)
Dim fName, Path, strSheet, strRef, strRng As Variant
xxDay = ""
Path = "C:\MMS\"
fName = "Book1.xlsm"
strSheet = "Sheet1"
strRng = Cells(row, 3).Address(, , xlR1C1)
strRef = "'" & Path & "[" & fName & "]" & strSheet & "'!" & strRng
xxDay = ExecuteExcel4Macro(strRef)
End Function
我在单元格中返回了#VALUE。我将它作为Sub运行,它将返回预期的结果。是否有可能让函数调用其自身的另一个函数?
Sub SubxxDay()
Dim fName, Path, strSheet, strRef, strRng, xxDay, row As Variant
row = 7
xxDay = ""
Path = "C:\MMS\"
fName = "Book1.xlsm"
strSheet = "Sheet1"
strRng = Cells(row, 3).Address(, , xlR1C1)
strRef = "'" & Path & "[" & fName & "]" & strSheet & "'!" & strRng
xxDay = ExecuteExcel4Macro(strRef)
MsgBox xxDay
End Sub
非常感谢任何回应。
答案 0 :(得分:1)
我建议一种可能的解决方法。方法如下:当UDF正在执行时,ExecuteExcel4Macro()
被称为后期绑定Excell.Application
实例的方法,但不会通过将导致错误的主机Application
对象。因此,应该创建该实例并在打开工作簿时保持可访问状态,并在工作簿关闭之前退出以释放操作系统资源。这是下面的代码。
将此代码放入VBAProject模块:
Function ExcelApp()
Static objApp As New clsExcelApp
Set ExcelApp = objApp.ExcelApp
End Function
Function xxDay(row) ' the code this function contains is almost all yours
Dim fName, Path, strSheet, strRef, strRng As Variant
xxDay = ""
Path = "C:\Test\"
fName = "Source.xlsx"
strSheet = "Sheet1"
strRng = Cells(row, 3).Address(, , xlR1C1)
strRef = "'" & Path & "[" & fName & "]" & strSheet & "'!" & strRng
xxDay = ExcelApp.ExecuteExcel4Macro(strRef) ' reference to ExcelApp object
End Function
创建类模块,为其指定名称clsExcelApp
,并将此代码放入其中:
Public ExcelApp
Private Sub Class_Initialize()
Set ExcelApp = CreateObject("Excel.Application")
' ExcelApp.Visible = True ' uncomment for debug
End Sub
Private Sub Class_Terminate()
ExcelApp.Quit ' the only class purpose is to quit app anyway at the end
Set ExcelApp = Nothing
End Sub