简体   繁体   中英

Share adodb Connection Between modules VBA

Is there a basic way to create a database connection in one module/form then be able to access the same database connection (left open) from another module?

I have a form that pops up requesting the SQL server, then from that gathers the databases for the user to select. Then when i go to try and use the connection it does not connect to the db declared Public in the other module?

Does this make sense and if so is there a way around?

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

That is my open connection function, but i cannot seem to access (correctly) the conn in another module, IE set rs = conn.execute("SELECT * FROM BLAH")

You should be able to declare. assign and open an ADODB.Connection then pass it along to another sub via the second sub's parameter(s).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM