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

标签 excel vba directory working-directory

我有一个位于网络文件夹中的 .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 调用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.



希望这可以帮助。

关于excel - 是否可以从位于网络文件夹中的文件加载 VBA 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238449/

相关文章:

excel - 使用总行查找表中的最后一个单元格列

perl - 使用 Excel::Writer::XLSX 创建表格后无法合并单元格

excel - 使用 InStr 搜索双引号

vba - 如何使用 VBA 获取文件的 MD5 十六进制哈希值?

file - 使用 BATCH 脚本检查目录中是否存在任何类型的文件

python - openpyxl生成的Excel文件打开时需要修复

excel - Power Query 中的逆透视列会创建无用的数据行

VBA,如果值喜欢

目录

linux - 将整个目录结构的每个文件复制到另一个的基本路径中