vba 从 Access 中的宏设计调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17413308/
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-08 16:01:06  来源:igfitidea点击:

Calling a Function from Macro Design In Access

vbams-accessaccess-vbams-access-2007

提问by SAM244776

I have written some sql queries, some sub procedures and have some saved imports.

我已经编写了一些 sql 查询、一些子过程并保存了一些导入。

Now I am trying to use the Macro Design in Access to provide a run button which will run these objects sequentially.

现在我正在尝试使用 Access 中的宏设计来提供一个运行按钮,该按钮将按顺序运行这些对象。

However I dont see any command for running a sun procedure, I can see OpenVisualBasicModule and Runcode.

但是我没有看到任何运行 sun 程序的命令,我可以看到 OpenVisualBasicModule 和 Runcode。

OpenVisualBaicModule is only opening my sub procedures and Run Code is asking for a function only.

OpenVisualBaicModule 只打开我的子程序,而运行代码只要求一个函数。

I created a function with all the sub procedure call inside. But thats not working while individually all of them work.

我创建了一个包含所有子过程调用的函数。但那是行不通的,而单独所有的人都可以工作。

Any suggestion what to do.

任何建议做什么。

回答by Rob van Meeuwen

Make sure your VBA code is placed inside a Function (not a SUB, that won't work). Create your function like:

确保您的 VBA 代码放在一个函数中(不是 SUB,那是行不通的)。创建您的功能,如:

Function DoSomething()
  'Do your stuff
End Function

Or if you want to execute a Sub, just create a Function that calls your sub, like:

或者,如果您想执行一个 Sub,只需创建一个调用您的 sub 的函数,例如:

Function DoSomething()
   Call YourSub()
End Function

Inside the Macro Design, add the 'RunCode' action (Macro Commands > RunCode) and call your function:

在宏设计中,添加“运行代码”操作(宏命令 > 运行代码)并调用您的函数:

DoSomething()

And voila, you're done.

瞧,你完成了。

回答by Andy G

As you are already using code, the Macro seems unnecessary. In the Property Sheet for the Button, find the OnClick row and type in there:

由于您已经在使用代码,因此宏似乎没有必要。在按钮的属性表中,找到 OnClick 行并在其中输入:

=YourFunctionName()

(this also has to be a Function, not a Sub-procedure; this is a peculiarity of Access)

(这也必须是一个函数,而不是一个子过程;这是 Access 的一个特性)

In your function you can use DoCmdto call any Macro Actions that you are using in your current Macro. Throw a MsgBox as the first line of your function to check that it is running.

在您的函数中,您可以DoCmd用来调用您在当前宏中使用的任何宏操作。抛出一个 MsgBox 作为函数的第一行来检查它是否正在运行。

You may be less familiar with the code, than a macro, but you will be able to add good comments to it, step-through and debug the code, use sensible error-handling - far easier than you can with a Macro.

与宏相比,您可能对代码不太熟悉,但您将能够为其添加好的注释、逐步调试和调试代码、使用合理的错误处理 - 比使用宏容易得多。