excel and sql queries through different subs or functions

和自甴很熟 提交于 2019-12-11 08:11:28

问题


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

来源:https://stackoverflow.com/questions/16436006/excel-and-sql-queries-through-different-subs-or-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!