是否可以从位于网络文件夹中的文件加载 VBA 代码?

Is it possible to load a VBA code from a file located in a network folder?

我有一个位于网络文件夹中的 .vba 文件,让我们称它为 helloworld.vba 在此文件中我有一个子函数 HelloFromTheOtherSide()

我正在尝试以编程方式加载此文件,以便我可以在我的 excel 实例中执行函数 HelloFromTheOtherSide()

为简单起见,假设这是内容:

Sub HelloFromTheOtherSide()
MsgBox ("hello there!")
End Sub

我已尝试按照这些说明进行操作 on how to dynamically add and run a VBA macro from Visual Basic 但这不是我在这里尝试做的,因为我希望能够 运行 调用 HelloFromTheOtherSide()

我正在尝试了解是否可以以我可以 运行 的方式以编程方式将 .vba 从文件夹加载到 excel 实例我实例中的函数。

如果可能的话,这将非常有用,因为我可以将所有 vba 代码存储在一个文件夹中,并在每次我想要 运行 特定内容时从那里加载它。

您可以同时使用 VBAVBScript 来调用 FunctionSub 来自另一个 Workbook:

VBA

Sub callExternalFunction()
    Dim xlApp As Object
    Dim xlBook As Object

    'Define Excel App
    Set xlApp = CreateObject("Excel.Application")
    'Open Workbook
    Set xlBook = xlApp.Workbooks.Open("\server\my\path\to\My library.xlsm", 0, True)

    'Call my Sub, with eventual parameters (if you don't have any, just call the Routine)
    xlApp.Run "Myfunction", "param_1", "param_2"

    'Quit and clean
    xlApp.Quit
    Set xlBook = Nothing
    Set xlApp = Nothing
End Sub

VBScript

Sub ExcelMacroExample() 
    Dim xlApp
    Dim xlBook

    'Define Excel App
    Set xlApp = CreateObject("Excel.Application")
    'Open Workbook
    Set xlBook = xlApp.Workbooks.Open("R:\my\network\path\My Workbook.xlsm", 0, True) 

    'Call my Sub, with eventual parameters (if you don't have any, just call the Routine)
    xlApp.Run "myRoutine"

    'Quit and clean
    xlApp.Quit

    Set xlBook = Nothing 
    Set xlApp = Nothing 

End Sub

编辑

您可以省略 Excel 应用程序初始化并直接使用此命令调用您需要的宏 (感谢@TimWilliams):

Application.Run "'MyBook.xls'!MyMacroName"

Note: As you can see they are pretty similar. Both codes are tested and working on my Excel.

希望对您有所帮助。