VBA 有参数时找不到我的宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5181863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:45:51  来源:igfitidea点击:

VBA cannot find my macro when it has parameters

vbaoffice-2010

提问by Dan Kelly

I am trying to write a macro that will be attached to a series of buttons in an Office 2010 backstage tab. Depending on the button clicked the Macro should be called with different parameters.

我正在尝试编写一个宏,该宏将附加到 Office 2010 后台选项卡中的一系列按钮。根据单击的按钮,应使用不同的参数调用宏。

The issue I am having is that if the Macro is defined as having parameters then VBA will display the "Macros" dialog box, with no Macros listed. Removing the parameters from the declaration will allow the macro to run, but it needs the Macros to make sense.

我遇到的问题是,如果宏定义为具有参数,则 VBA 将显示“宏”对话框,但未列出任何宏。从声明中删除参数将允许宏运行,但它需要宏才能有意义。

The VBA being used is below:

正在使用的 VBA 如下:

Sub NewDocs(docType As String, docTemplate As String)
   Dim sMyShellCommand As String
   sMyShellCommand = "C:\NewDocs.exe " & docType & docTemplate
   WordBasic.Shell (sMyShellCommand)
End Sub

Any ideas

有任何想法吗

回答by Dante May Code

If I've got your question right....

如果我问对了你的问题......

Because there is no place in the Macrosdialog box for entering parameters, the macros with parameters are simply not shown.

因为对话框中没有输入参数的地方,所以根本没有显示带参数的宏。

If you want to make them visible in the dialog box, you can enumerate those functions you need (and I hope it is not a big number).

如果你想让它们在对话框中可见,你可以枚举你需要的那些函数(我希望它不是一个很大的数字)。

For example,

例如,

Sub NewDocs1
  Dim docType As String
  Dim docTemplate As String

  docType = "the type you want"
  docTemplate = "the template you want"

  NewDocs docType, docTemplate
End Sub

In addition, as you said in the question, you wanted the macro to run when buttons were pressed. Then there is no need to make the macro visible in the dialog box (which saves your labor). Simply associate it with the button with correct parameters.

此外,正如您在问题中所说,您希望宏在按下按钮时运行。这样就不需要在对话框中使宏可见(这样可以节省您的劳动)。只需将其与具有正确参数的按钮相关联。

回答by shg

You can pass arguments from the Macro dialog. For example, if you have this macro

您可以从宏对话框传递参数。例如,如果你有这个宏

Sub myMacro(n As Long)
    MsgBox n
End Sub

To run it, enter

要运行它,请输入

mymacro 1000

... and press the Run button.

...然后按运行按钮。

回答by Juancentro

You can't call functions or subs with parameters from UI components, just subs without parameters. The best solution is to create a parameter free sub for each button you need to associate with, and call the parameterized sub or function from inside each sub

您不能从 UI 组件调用带有参数的函数或子程序,只能调用没有参数的子程序。最好的解决方案是为您需要关联的每个按钮创建一个无参数子程序,并从每个子程序内部调用参数化子程序或函数