vba AutoExec 模块未启动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21991482/
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
AutoExec Module not Initiating
提问by user2119980
My data storage form has a new module (AutoExec) which is meant to test the connection to a SQL server db upon opening the form. Only it is not firing when opened. I was wondering if there was something in my code causing this, this is my first Module so I am not familiar with the proper forms yet.
我的数据存储表单有一个新模块 (AutoExec),用于在打开表单时测试与 SQL 服务器数据库的连接。只有它在打开时不会触发。我想知道我的代码中是否有什么东西导致了这个,这是我的第一个模块,所以我还不熟悉正确的形式。
Public Sub AutoExec()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
Set cnn = New ADODB.Connection
cnn.Open "Provider=SQLOLEDB; Data Source=DB\P003,49503; Initial Catalog=HRLearnDev;" _
& "User Id=USERNAME; Password=PASSWORD;"
If cnn.State = adStateOpen Then
MsgBox ("You have an established connection.")
Else
MsgBox ("Cannot connect to remote server. Data will be stored locally to CDData Table until application is opened again.")
End If
cnn.Close
Dim rst As New ADODB.Recordset
End Sub
回答by HansUp
When a database includes a macro named AutoExec, Access will run that macro at database startup.
当数据库包含名为AutoExec的宏时,Access 将在数据库启动时运行该宏。
In order for that to work, AutoExecmust be an Access macro object. In your case, you have a VBA procedure named AutoExec. Since that is not a macro object, Access does not run the procedure automatically at database startup.
为了使其工作,AutoExec必须是 Access宏对象。在您的情况下,您有一个名为AutoExec的 VBA 过程。由于那不是宏对象,Access 不会在数据库启动时自动运行该过程。
I suggest you create a VBA function ...
我建议你创建一个 VBA 函数......
Public Function Startup()
Add the code from the body of your AutoExecprocedure to the function.
将AutoExec过程主体中的代码添加到函数中。
Then create a new Access macro (an actual Access macro object --- on the ribbon in Access 2007, choose Create->Macro), use the macro RunCode
action to run your new Startup()
function. Name that macro object as AutoExec.
然后创建一个新的 Access 宏(一个实际的 Access 宏对象 --- 在 Access 2007 的功能区上,选择Create->Macro),使用宏RunCode
操作来运行您的新Startup()
功能。将该宏对象命名为AutoExec。
Here is a screenshot of my simple AutoExecexample macro open in Design View.
这是我在设计视图中打开的简单AutoExec示例宏的屏幕截图。