共享模块VBA之间的adodb连接

有一种基本的方法来创build一个模块/表单中的数据库连接,然后能够从另一个模块访问相同的数据库连接(打开)?

我有一个popup窗体,请求SQL服务器,然后从中收集数据库供用户select。 那么当我去尝试和使用连接它不连接到其他模块中声明的公共数据库?

这是否有道理,如果有,是否有办法解决?

Public conn As ADODB.Connection Public Function openConnection(Optional DB As String) Dim str As String str = "Provider=SQLOLEDB;Server=" & Me.tbx_serverName.Text If (Not IsEmpty(DB)) Then str = str & ";Database=" & DB End If str = str & ";UID=" + tbx_dbuser.Text + " ;PWD=" + tbx_dbpass.Text + ";" On Error Resume Next If conn Is Nothing Or conn.Status = 0 Then Set conn = New ADODB.Connection conn.Open str End If If (conn.State = adStateOpen) Then If (Not IsEmpty(DB)) Then Me.lbl_connecteddb.Caption = "Connected to Database:" + DB Else Me.lbl_connecteddb.Caption = "Connected to Database:" + Me.ComboBox1.SelText End If Else Me.lbl_connecteddb.Caption = "Error" End If End Function 

这是我的开放连接function,但我似乎无法访问(正确)在另一个模块的连接,IE设置rs = conn.execute(“select*从BLAH”)

你应该可以申报。 分配并打开一个ADODB.Connection然后通过第二个子parameter passing给另一个子。

 sub Start_Here() Dim str As String, conn As ADODB.Connection str = "Provider=SQLOLEDB;Server=" & Me.tbx_serverName.Text If (Not IsEmpty(DB)) Then str = str & ";Database=" & DB End If str = str & ";UID=" + tbx_dbuser.Text + " ;PWD=" + tbx_dbpass.Text + ";" On Error Resume Next If conn Is Nothing Or conn.Status = 0 Then Set conn = New ADODB.Connection conn.Open str End If Call Then_Here(conn) 'remember to close conn before exit end sub sub Then_Here(next_conn As ADODB.Connection) debug.print next_conn.Status 'use open next_conn here end sub