I have a few procedures that write records to a table, such as the example below which runs when the database starts and writes to a user log table. From what I understand, when you open a recordset object it is always important to close it and set it to "nothing" before the procedure ends.
I am now adding some basic error handling to all the code modules in my database. In the example below, should the two lines under "clean up" be placed after the "ExitHere:" line? I would assume that if an error occurs when trying to write to the table, we would still want to close the recordset after the error handler message appears. However, if I place the clean up statements after "ExitHere:" and an error is triggered before the recordset is created or opened, would that then cause an error when I try to close the non-existent recordset?
Code:
Private Sub Form_Open(Cancel As Integer)
On Error GoTo ErrHandler
'hide startup form
Me.Visible = False
'maximize application window and minimize ribbon
DoCmd.RunCommand acCmdAppMaximize
CommandBars.ExecuteMso "MinimizeRibbon"
'get version #
Dim VersionNum As String
VersionNum = DLookup("Version", "tblVersion")
'setup and open UserLog recordset
Dim UserLogRS As New ADODB.Recordset
UserLogRS.Open "tblUserLog", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
'Add new record to UserLog
With UserLogRS
.AddNew
![UserID] = (Environ$("Username"))
![LoginTime] = Now()
![Version] = VersionNum
.Update
End With
'clean up
UserLogRS.Close
Set UserLogRS = Nothing
ExitHere:
DoCmd.Close acForm, "frmStartUp", acSaveNo
DoCmd.OpenForm "frmMain"
Exit Sub
ErrHandler:
MsgBox "An unexpected error occurred. If this problem persists please contact the system administrator and reference the following information:" _
& vbNewLine & vbNewLine & "Error Number: " & Err.Number & vbNewLine & "Description: " & Err.Description, _
vbCritical, "VBA Error"
Resume ExitHere
End Sub