gpt4 book ai didi

Excel-vba Application.Run 替代方法以使用命名参数运行宏

转载 作者:行者123 更新时间:2023-12-04 22:28:04 24 4
gpt4 key购买 nike

如何使用 Application.Run带有命名参数?基于此MS documentation :

You cannot use named arguments with this method. Arguments must be passed by position.



对于我的代码目的而言,强制按位置传递参数的解决方案似乎有点不灵活,即创建一个宏,通过传递一些参数来运行其他人的宏。示例如下:

Sub MyMacro()

Dim macroName as String
Dim foo as String
Dim bar as String

macroName = "'quux.xlam'!quuz"
foo = "thud"
bar = "baz"

' arguments pass by position
' this method works
Application.Run macroName, foo, bar

' however, I intend to remove position dependency to allow flexibility
' hence, I'd like to pass argument by name, as below
Application.Run macroName, foo:=foo, bar:=bar ' or below
Application.Run macroName, bar:=bar, foo:=foo ' both raise compile error

End Sub


' Below is a macro from Add-In quux.xlam
Sub quuz(foo as String, bar as String)

MsgBox foo & bar

End Sub

我的问题类似于 this但它没有回答我的问题。那么我怎样才能找到 Application.Run 的替代品? ?

情景/假设

我有自己的宏。同时,我正在使用其他人的宏(例如来自加载项)。我们俩都没有沟通,也没有适当的插件文档。可能的情况如下(2):
  • 插件代码是固定的
  • 我知道我必须通过foobar但不知道顺序。例如,我无法打开代码 bcs 宏受密码保护。
  • 我的代码是固定的
  • 其他人正在使用我的宏。他们知道当他们使用我的宏时,他们必须接受两个参数 foobar但位置不明。
  • 我的宏受密码保护。
  • 这种情况更容易,因为我至少可以做我的一部分并创建适当的文档。

  • 我的实际情况更多的是第二个,所以我认为我现在的解决方案只是按位置传递参数,并为其创建适当的文档。但我只是在测试第 1 种情况,如果有人以前遇到过或有任何想法解决它?

    最佳答案

    解决方案 1
    您可以自己编写一个包装程序,将变量按正确的顺序排序。

    Sub test()
    quuzWrapper bar:="bar", foo:="foo"
    End Sub

    Sub quuzWrapper(foo as String, bar as String)
    Application.Run "quuz", foo, bar
    End Sub



    ' Below is a macro from Add-In quux.xlam
    Sub quuz(foo as String, bar as String)
    MsgBox foo & bar
    End Sub

    解决方案 2
  • 确保您的 VBA 加载项具有唯一的 VBA 名称并且不称为 VBAProject .例如称它为quuxAddIn .
  • 在您的项目(不是插件)中设置一个引用(在 VB 编辑器菜单中:Extras > References)并选择 quuxAddIn .
  • 然后你可以像这样调用你的子:
     quuxAddIn.quuz bar:="bar", foo:="foo"

  • 由于评论而编辑:
    如果您设置了对项目智能感知(工具提示)的引用,那么在您输入 quuxAddIn.quuz 之后,它应该会显示带有参数的工具提示。这样您也可以按名称提交参数。 (但实际上加载项必须存在才能将其添加为引用,因此这仅适用于您的方案 1)。在您的方案 2 中,只有您描述的解决方案和使用具有固定顺序的 Application.Run 的解决方案可用。 • 然而,良好的文档应该是强制性的。

    关于Excel-vba Application.Run 替代方法以使用命名参数运行宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952903/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com