【问题标题】:A function within a function in vba?vba中函数内的函数?
【发布时间】:2015-04-08 17:19:32
【问题描述】:

这是我在单元格中使用的函数的简化版本(例如 =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

非常感谢任何回复。

【问题讨论】:

  • 您不只是将单元格的引用创建为公式吗?
  • 在 UDF 中禁止执行 Excel4Macro 调用,确切地说是在 UDF 工作时。但是很少有解决方法可以避免此类限制。请参阅 thisthisthis。这里还有类似的question

标签: excel vba


【解决方案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

【讨论】:

  • 大力帮助,非常感谢!现在我必须确切地了解你做了什么。你给了我一个很好的解释,所以我应该能够通过它。再次感谢。
猜你喜欢
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多