我有一个位于网络文件夹中的 .vba 文件,我们称之为 helloworld.vba
在这个文件里面我有一个子函数HelloFromTheOtherSide()
.
我正在尝试以可以执行函数 HelloFromTheOtherSide()
的方式以编程方式加载此文件在我的excel实例中。
想象一下,这是为了简单起见的内容:
Sub HelloFromTheOtherSide()
MsgBox ("hello there!")
End Sub
我已尝试遵循这些说明 on how to dynamically add and run a VBA macro from Visual Basic但这不是我在这里想要做的,因为我希望能够运行调用
HelloFromTheOtherSide()
.我试图了解是否可以以编程方式将 .vba 从文件夹加载到 excel 实例中,而我可以在我的实例中运行这些函数。
如果可能的话,这将非常有用,因为我可以将所有 vba 代码存储在一个文件夹中,并在每次我想运行特定的东西时从那里加载它。
最佳答案
您可以同时使用 VBA 或 VBScript 调用Function
或 Sub
来自另一个 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.
希望这可以帮助。
关于excel - 是否可以从位于网络文件夹中的文件加载 VBA 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238449/