Object Oriented Programming with VBA
TIP
This post demonstrates how to create a simple class in VBA and to use it in the regular modules. Classes allows to package different properties and methods into a reusable “container”. It is extremely useful when the program constantly calling these methods/properties. This example will create a ADO database class which allows to connect to a MSSQL database. Consider this as an extension to the default ADODB class.
Prerequisite
The following references must be checked in VBA so that the example can be ran without errors.
- Microsoft ActiveX Data Objects Recordset 2.x Library
- Microsoft ActiveX Data Objects 2.0 Library
- Microsoft ADO Ext. 2.x for DLL and Security
Declare the variables
you gonna use inside the class module. Since we only want these variables to be recognized within this class. We will declare them to be Private.
Option Explicit
Private conn as ADODB.connection
Private dbName as String
GET/LET
this is VBA’s way of reading (GET) and writing (LET) class properties.
'write and read database name property
Public Property Get DataBaseName() As String
DataBaseName = dbName
End Property
Public Property Let DataBaseName(value As String)
dbName = value
End Property
'read database connection string
Public Property Get ConnectionString()
ConnectionString = conn.ConnectionString
End Property
Constructors
Every class will need (at least) one initialization procedure. This happens when you declare a class object in the regular module (a.k.a. main program). The first way of initializing the class (using connection string directly):
Public Sub Initialize(ByRef connectionStr As String)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This sub will open a connection specified by a connection string
'connectionStr: connection string
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Open connection to database using connectionStr as connection string
Set conn = New ADODB.Connection
With conn
On Error Resume Next
.ConnectionString = connectionStr
.ConnectionTimeout = 0 ' indefinite wait...
.Open
End With
End Sub
The second way of initializing the class (using server name, catalog/database name, and credentials).
Public Sub InitializeSQLDB(dataSource As String, catalog As String, Optional userID As String = "")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This sub initializes the connection to an SQL Server DB
'dataSource: datasource i.e. server name
'catalog: database name
'userID: user ID
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim connStr As String
Dim pwd As String
'Create connection string
If Len(userID) = 0 Then
''SQLNCLI11' windows credentials
connStr = "Provider='SQLNCLI11';Data Source= " & dataSource & ";" & "Initial Catalog=" & catalog & ";" _
& "Integrated Security= 'SSPI';" & "Persist Security Info=False;" & "QuotedID=No"
Else
'FrmPassword.Show
pwd = InputBox("Password?") 'FrmPassword.Password 'Utils.GetInput("Enter password :")
connStr = "Provider='SQLNCLI11';Data Source= " & dataSource & ";" & "Initial Catalog=" & catalog & ";" _
& "User ID=" & userID & ";" & "Password=" & pwd & ";"
End If
With Me
.DataBaseName = catalog ' Set property
End With
Me.Initialize connStr
End Sub
Now, write some methods/functions
you want to do inside the class. The very first thing I want this class to do is to execute an SQL query.
Public Sub ExecuteSQLInDB(ByRef sqlStr As String)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This sub will Execute SQL in sqlStr
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
With conn
.Execute sqlStr
End With
End Sub
Next, I want to have a way to clear out the records of an existing table.
Public Sub ClearTable(tblName As String)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This function will clear content of tblName in DB
'tblName: name of table to cleared
' adoConn: connection to database
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim sqlStr As String
sqlStr = "DELETE FROM [" & tblName & "]"
On Error Resume Next
Application.StatusBar = "Clearing Table [" & tblName & "]"
Me.ExecuteSQLInDB sqlStr
If Err.Number > 0 Then
Debug.Print tblName & " No Clearing Took Place... Err description" + Err.Description
End If
Application.StatusBar = False
End Sub
Finally, I want to have a function to clear out all tables in the database. To do this in a fancier way, we will create a generic “ApplyAll” function as we probablly want to do other similar “apply for all” operations in the future.
Public Function ApplyMethodToAllTablesInDB(funcName As String) As Integer
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This function is a dispatcher of function/method called funcName on all tables in the database
' funcName should have a parameter which is a table name
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim recSet As ADODB.Recordset
Dim tblName As String
Dim tblNum As Integer
Set recSet = conn.OpenSchema(adSchemaTables, Array(Empty, Empty, Empty, "TABLE"))
tblNum = 0
Do While Not recSet.EOF
tblName = recSet.Fields("TABLE_NAME").value
CallByName Me, funcName, VbMethod, tblName
recSet.MoveNext
tblNum = tblNum + 1
Loop
ApplyMethodToAllTablesInDB = tblNum
Set recSet = Nothing
End Function
Public Function ClearAllTables() As Integer
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This function clears all tables in DB of its contents
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ClearAllTables = Me.ApplyMethodToAllTablesInDB("ClearTable")
End Function
Last but not the least, we want to clean up things
Especially when we are dealing with the SQL objects that could explode the computer’s memory if we don’t release them properly.
Friend Sub Class_Terminate()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Terminates class. Important in a class like this since connection object
' needs to be released to avoid tying up memory
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Not conn Is Nothing Then ' This check important as invoking methods on a null object will cause errors.
If conn.State = adStateOpen Then
conn.Close
End If
End If
Set conn = Nothing
End Sub
The class is pretty much completed. Now let’s try it out in our regular modules (main program).
Sub Main()
Dim objSQL As clsMSSQL
Set objSQL = New clsMSSQL
objSQL.InitializeSQLDB "(local)", "Demo_Db", "sa"
MsgBox "Database " & objSQL.DataBaseName & " is connected successfully!"
objSQL.ClearAllTables
MsgBox "Database tables are cleared out!"
Set objSQL = Nothing
End Sub
Yay!