I have an excel sheet which i use with an access database. I want to open the database and use different sub routines with different queries. However i don't know hot to publically assign an variable to use the database so i have to create the connection within each subroutine and open and close this.
I have a fealing that this must be able to do smarter so i don't have the same code written all over it.
I open the database with the following code and have to do this over and over for every query:
Public Sub copy_to_sql()
Dim Cn As New ADODB.Connection
Dim Rs As New ADODB.Recordset
Dim Cmd As New ADODB.Command
Dim strMDB As String
strMDB = ThisWorkbook.Path & "\klantserverinfo.accdb"
' Set Cn = CreateObject("ADODB.Connection")
Cn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" & strMDB
Cn.Open
'--- Do some queries like
SqlQuery = "SELECT * FROM database"
Set Cmd.ActiveConnection = Cn
Cmd.CommandText = SqlQuery
Cmd.CommandType = adCmdText
Set Rs.Source = Cmd
Rs.Open
Cn.close
End Sub
Does anyone know how to do this better?
Ps, I use Office 2010 and the database used is an access 2010 database