SQL in Excel VBA - Best Practices
How to use ADODB.Connection in VBA?
Section titled “How to use ADODB.Connection in VBA?”Requirements:
Section titled “Requirements:”Add following references to the project:
Declare variables
Section titled “Declare variables”Private mDataBase As New ADODB.ConnectionPrivate mRS As New ADODB.RecordsetPrivate mCmd As New ADODB.CommandCreate connection
Section titled “Create connection”a. with Windows Authentication
Section titled “a. with Windows Authentication”Private Sub OpenConnection(pServer As String, pCatalog As String) Call mDataBase.Open("Provider=SQLOLEDB;Initial Catalog=" & pCatalog & ";Data Source=" & pServer & ";Integrated Security=SSPI") mCmd.ActiveConnection = mDataBaseEnd Subb. with SQL Server Authentication
Section titled “b. with SQL Server Authentication”Private Sub OpenConnection2(pServer As String, pCatalog As String, pUser As String, pPsw As String) Call mDataBase.Open("Provider=SQLOLEDB;Initial Catalog=" & pCatalog & ";Data Source=" & pServer & ";Integrated Security=SSPI;User ID=" & pUser & ";Password=" & pPsw) mCmd.ActiveConnection = mDataBaseEnd SubExecute sql command
Section titled “Execute sql command”Private Sub ExecuteCmd(sql As String) mCmd.CommandText = sql Set mRS = mCmd.ExecuteEnd SubRead data from record set
Section titled “Read data from record set”Private Sub ReadRS() Do While Not (mRS.EOF) Debug.Print "ShipperID: " & mRS.Fields("ShipperID").Value & " CompanyName: " & mRS.Fields("CompanyName").Value & " Phone: " & mRS.Fields("Phone").Value Call mRS.MoveNext LoopEnd SubClose connection
Section titled “Close connection”Private Sub CloseConnection() Call mDataBase.Close Set mRS = Nothing Set mCmd = Nothing Set mDataBase = NothingEnd SubHow to use it?
Section titled “How to use it?”Public Sub Program() Call OpenConnection("ServerName", "NORTHWND") Call ExecuteCmd("INSERT INTO [NORTHWND].[dbo].[Shippers]([CompanyName],[Phone]) Values ('speedy shipping','(503) 555-1234')") Call ExecuteCmd("SELECT * FROM [NORTHWND].[dbo].[Shippers]") Call ReadRS Call CloseConnectionEnd SubResult
Section titled “Result”ShipperID: 1 CompanyName: Speedy Express Phone: (503) 555-9831
ShipperID: 2 CompanyName: United Package Phone: (503) 555-3199
ShipperID: 3 CompanyName: Federal Shipping Phone: (503) 555-9931
ShipperID: 4 CompanyName: speedy shipping Phone: (503) 555-1234
