Checking form's CountOfLines - vba

I try to improve a report I made to document databases, by adding a VBA line count to Modules and Forms. The following code works perfectly in a standard module:
Sub test()
Dim accObj As AccessObject, bwasOpen As Boolean, objName As String
objName = "Form1"
Set accObj = CurrentProject.AllForms(objName)
bwasOpen = accObj.IsLoaded
If Not bwasOpen Then
DoCmd.OpenForm objName, acDesign, WindowMode:=acHidden
End If
If Forms(objName).HasModule Then
DoCmd.OpenModule "Form_" & objName
Debug.Print Modules("Form_" & objName).CountOfLines
End If
If Not bwasOpen Then
DoCmd.Close acForm, objName, acSaveNo
End If
End Sub
But when I use a similar code in the report itself, I have an error. And since that error is happening in the class module (the report), I feel a bit stuck with debugging. The code in the report:
Set accObj = CurrentProject.AllForms(objName)
bwasOpen = accObj.IsLoaded
If Not bwasOpen Then
DoCmd.OpenForm objName, acDesign, WindowMode:=acHidden 'Breaks here
End If
If Forms(objName).HasModule Then
DoCmd.OpenModule "Form_" & objName
GetExtraInfo = Modules("Form_" & objName).CountOfLines
End If
If Not bwasOpen Then
DoCmd.Close acForm, objName, acSaveNo
End If
The code is called from a report control using =GetExtraInfo(). The whole thing works well, except this new part where I want to return the CountOfLines for Forms.
Update: I have added some error trapping, and it gives error:
2486 - You can't carry out this action at the present time
The whole db can be downloaded here, its's only 300 KB. The report is named "rptObjList".
The "bad" code has been commented out. It is an Access 2003 db.
Thanks for your help.

Your code opens a form and checks its .HasModule property. And if the form has a module, you open that module to check .CountOfLines. However, you need not open the module to determine its .CountOfLines. And I would try to avoid opening the form, too.
? VBE.ActiveVBProject.VBComponents("Form_Form1").CodeModule.CountOfLines
6
If you ask for .CountOfLines for a module which doesn't exist, such as the following, you can trap error #9 ('Subscript out of range') to give you an alternative to checking the .HasModule property:
? VBE.ActiveVBProject.VBComponents("bogus").CodeModule.CountOfLines
Or you could check for the code module with a function similar to minimally tested ModuleExists() outlined below.
Note I'm unsure how helpful my suggestions will be because I struggled to follow your code. Furthermore I unwisely chose to step through the code behind rptObjList and became frustrated by all the unhandled errors when it calls GetDesc() for objects which have no Description property. I just gave up.
Public Function ModuleExists(ByVal pModule As String, _
Optional ByVal pProject As String = "") As Boolean
Dim blnReturn As Boolean
Dim objVBProject As Object
Dim strMsg As String
On Error GoTo ErrorHandler
If Len(pProject) = 0 Then
Set objVBProject = VBE.ActiveVBProject
Else
Set objVBProject = VBE.VBProjects(pProject)
End If
blnReturn = Len(objVBProject.VBComponents(pModule).Name) > 0
ExitHere:
Set objVBProject = Nothing
ModuleExists = blnReturn
Exit Function
ErrorHandler:
Select Case Err.Number
Case 9 ' Subscript out of range
' no such module; function returns False
Case Else
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ") in procedure ModuleExists"
MsgBox strMsg
End Select
GoTo ExitHere
End Function

Related

Run-time error '2467': The expression you entered refers to an object that is closed or doesn't exist

I am running into a 2467 error after the following code ():
Option Compare Database
Option Explicit
Private Sub CmdReject_Click()
Dim lngID As Long
lngID = Me.ID
If Me.Dirty Then Me.Dirty = False
DoCmd.Close , ""
Beep
MsgBox "Issue has been saved.", vbInformation, ""
NewFormIssue (lngID)
End Sub
Private Sub NewFormIssue(lngID As Long)
DoCmd.OpenForm "Frm_Issue_Entry", acNormal, , , acFormAdd
Me.Person.Value = DLookup("[Previous_Person]","[tbl_Issue_Log]", "[ID] = " lngID)
End Sub
The run-time error occurs during the Me.Person.Value = DLookup("[Person]","[tbl_Issue_Log]", "[ID] = " lngID) line.
I am trying to use the ID of the previous form to populate 11 fields on this new form so the user doesn't have to redo everything using dlookup, which worked before but I can't seem to find why it just stopped working...
I think I figured out what was happening (at least from a high level standpoint). The Me was still pointing to the previously closed form, not the new form added, causing the error. I fixed the issue by using Form_Frm_Issue_Entry.Person.Value instead, but I am not sure why it worked previously.

How do I correct a MS Access Run-Time error '2498' in Access VBA?

I am trying to write a code that will print out my current form for the current record. This is what I am using:
Private Sub PrintCommand_Click()
Dim myform As Form
Dim pageno As Long
pageno = Me.CurrentRecord
Set myform = Screen.ActiveForm
DoCmd.SelectObject acForm, myform.Name, True
DoCmd.PrintOut acPages, pageno, pageno, , 1
DoCmd.SelectObject acForm, myform.Name, False
End Sub
When I dimension "pageno" as an integer, it gives me an overflow error for some of my records that exceed 65000. So, I dimensioned it as a long data type, but then I receive the following error:
Run-time error '2498': An expression you entered is the wrong data type for one of the arguments."
I also tried making "pageno" a variant data type, and I received the same 2498 error message. Any suggestions on either a way to fix this or another work around for printing my form for the current record?
Update: This works and accomplishes what I was going for...
Private Sub PrintCommand_Click()
'Print out the current record
Me.Filter = "[Quote Number] = " & QuoteNumberEntry.Value
Me.FilterOn = True
DoCmd.PrintOut
Me.Filter = ""
Me.FilterOn = False
End Sub

How to refill combobox with similar records based on what user types

I'm currently building a form where a user can look up a tool based on the description or part number.
I want user to be able to type any letters into the combobox that I have tied to a query listing all my tools and the combobox will repopulate itself with the tools most similar to what is present in their combobox. For example, if they start typing wre, then tools that have similar characters will start appearing in the combobox such as wrench, torque wrench, power wrench, etc.
I've tried looking around for other people's solutions to this but either I didn't fully comprehend the existing solution (I'm fairly new to Access) or it wasn't what I was looking for. I've seen that people suggested using a listbox instead but I really don't want to go down that route.
I was thinking about using what the user types in the combobox and my VBA code will pick up the "change event" and requery the combobox on the fly by using their input as the like criteria for the new query.
Is this a possible route? Will it be slower? Is there a better route?
I'm hoping someone can show some examples on how to achieve what I'm looking for.
The search as you type feature is very useful! With a textbox and a listbox, you can setup a dynamic search tool that will filter a list for approximate matches as you type. The textbox has four events associated with it, as seen here.
The code behind the form looks like this. Pay attention to the part in bold. This is where we create a string of SQL commands, and utilize the SQL Like operator, to get dynamic matches as we type. Pay attention to the text in bold below.
Option Compare Database
Option Explicit On
Private blnSpace As Boolean 'INCLUDE THIS LINE ON YOUR FORM
Private Sub btnClearFilter_Click()
'CODE FOR THE RED "X" BUTTON TO CLEAR THE FILTER AND SHOW ALL
On Error Resume Next
Me.txtSearch.Value = ""
txtSearch_Change()
End Sub
Private Sub txtSearch_Change()
'CODE THAT HANDLES WHAT HAPPENS WHEN THE USER TYPES IN THE SEARCH BOX
Dim strFullList As String
Dim strFilteredList As String
If blnSpace = False Then
Me.Refresh 'refresh to make sure the text box changes are actually available to use
'specify the default/full rowsource for the control
strFullList = "SELECT RecordID, First, Last FROM tblNames ORDER BY First;"
'specify the way you want the rowsource to be filtered based on the user's entry
strFilteredList = "SELECT RecordID, First, Last FROM tblNames WHERE [First] LIKE ""*" & Me.txtSearch.Value &
"*"" OR [Last] LIKE ""*" & Me.txtSearch.Value & "*"" ORDER BY [First]"
'run the search
fLiveSearch Me.txtSearch, Me.lstItems, strFullList, strFilteredList, Me.txtCount
End If
End Sub
Private Sub txtSearch_KeyPress(KeyAscii As Integer)
'NECESSARY TO IDENTIFY IF THE USER IS HITTING THE SPACEBAR
'IN WHICH CASE WE WANT TO IGNORE THE INPUT
On Error GoTo err_handle
If KeyAscii = 32 Then
blnSpace = True
Else
blnSpace = False
End If
Exit Sub
err_handle:
Select Case Err.Number
Case Else
MsgBox "An unexpected error has occurred: " & vbCrLf & Err.Description &
vbCrLf & "Error " & Err.Number & "(" & Erl() & ")"
End Select
End Sub
Private Sub txtSearch_GotFocus()
' USED TO REMOVE THE PROMPT IF THE CONTROL GETS FOCUS
On Error Resume Next
If Me.txtSearch.Value = "(type to search)" Then
Me.txtSearch.Value = ""
End If
End Sub
Private Sub txtSearch_LostFocus()
' USED TO ADD THE PROMPT BACK IN IF THE CONTROL LOSES FOCUS
On Error Resume Next
If Me.txtSearch.Value = "" Then
Me.txtSearch.Value = "(type to search)"
End If
End Sub
Finally, in a regular module, you will need this script.
Option Compare Database
Option Explicit On
'************* Code Start **************
' This code was originally written by OpenGate Software
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
' OpenGate Software http://www.opengatesw.net
Function fLiveSearch(ctlSearchBox As TextBox, ctlFilter As Control,
strFullSQL As String, strFilteredSQL As String, Optional ctlCountLabel As Control)
Const iSensitivity = 1 'Set to the number of characters the user must enter before the search starts
Const blnEmptyOnNoMatch = True 'Set to true if you want nothing to appear if nothing matches their search
On Error GoTo err_handle
'restore the cursor to where they left off
ctlSearchBox.SetFocus
ctlSearchBox.SelStart = Len(ctlSearchBox.Value) + 1
If ctlSearchBox.Value <> "" Then
'Only fire if they've input more than two characters (otherwise it's wasteful)
If Len(ctlSearchBox.Value) > iSensitivity Then
ctlFilter.RowSource = strFilteredSQL
If ctlFilter.ListCount > 0 Then
ctlSearchBox.SetFocus
ctlSearchBox.SelStart = Len(ctlSearchBox.Value) + 1
Else
If blnEmptyOnNoMatch = True Then
ctlFilter.RowSource = ""
Else
ctlFilter.RowSource = strFullSQL
End If
End If
Else
ctlFilter.RowSource = strFullSQL
End If
Else
ctlFilter.RowSource = strFullSQL
End If
'if there is a count label, then update it
If IsMissing(ctlCountLabel) = False Then
ctlCountLabel.Caption = "Displaying " & Format(ctlFilter.ListCount - 1, "#,##0") & " records"
End If
Exit Function
err_handle:
Select Case Err.Number
Case 91 'no ctlCountLabel
'exit
Case 94 'null string
'exit
Case Else
MsgBox "An unexpected error has occurred: " & vbCrLf & Err.Description &
vbCrLf & "Error " & Err.Number & vbCrLf & "Line: " & Erl()
End Select
End Function
The code comes from this link:
http://www.opengatesw.net/ms-access-tutorials/Access-Articles/Search-As-You-Type-Access.html

Trouble trapping 2501 error

I am sending data from frmSearchEmployeeWorksheets to frmStatsCorr which runs a query (qryStatsCorr). On frmStatsCorr I am checking to make sure the query returns records otherwise I will Msg the user and return to the search form. My problem is that I am having problems 'ignoring' the 2501 caused by the DoCmd.OpenForm ("frmStatsCorr") which I learned here on Stackoverflow...
What am I doing wrong that is causing me major Access VBA Frustration??
This is the sub on the Search form (frmSearchEmployeeWorksheets):
Private Sub btnSearch_Click()
' I only change focus to force the updated data to submit to query
Me.[txtEmployee].SetFocus
Me.txtShift.SetFocus
If txtUnit = "7" Then
'First close the form in order to update
DoCmd.Close acForm, "frmStatsCorr"
' Open Stats form
On Error GoTo myErr
**DoCmd.OpenForm ("frmStatsCorr") 'causes error**
End If
myExit:
Exit Sub
myErr:
Echo True
If Err.Number = 2501 Then GoTo myExit
MsgBox Err.Description
GoTo myExit
End Sub
In frmStatsCorr I simply check to make sure the query returns records if not I inform the user, close the form, and return to the frmSearchEmployeeWorksheets
Private Sub Form_Load()
If strFormStatus = "view" Then
If DCount("*", "qryStatsCorr") = 0 Then
MsgBox "Your search does not produce any results. Try a different search.", vbOKOnly
DoCmd.Close
DoCmd.OpenForm ("frmSearchEmployeeWorksheets")
Exit Sub
End If
txtDay = WeekdayName(Weekday(Me.WorkDate)) 'This line returns an error so I check for an empty query and return to the search form.
Me.[WorkDate].SetFocus
Me.txtUnit.Enabled = False...
I'm unsure how well I understand your code or the logic behind it. My hunch is you should check the DCount result from btnSearch_Click, and not fiddle with closing then re-opening frmStatsCorr, and having frmStatsCorr close itself when it contains no data. Just do not open frmStatsCorr when it will not contain data.
If the current form (frmSearchEmployeeWorksheets) which holds your btnSearch_Click procedure contains unsaved data changes, you can save them with Me.Dirty = False
Private Sub btnSearch_Click()
Dim strPrompt As String
If Me.Dirty Then ' unsaved data changes
Me.Dirty = False ' save them
End If
If Me.txtUnit = "7" Then
If DCount("*", "qryStatsCorr") = 0 Then
strPrompt = "Your search does not produce any results. " & _
"Try a different search."
MsgBox strPrompt, vbOKOnly
Else
' if frmStatsCorr is open, just Requery
' else open frmStatsCorr
If CurrentProject.AllForms("frmStatsCorr").IsLoaded Then
Forms("frmStatsCorr").Requery
Else
DoCmd.OpenForm "frmStatsCorr"
End If
' uncomment next line to close current form
'DoCmd.Close acForm, Me.Name
End If
End If
End Sub
If frmStatsCorr is open and you need to check whether it is in Design View, examine its CurrentView property.
Forms("frmStatsCorr").CurrentView ' Design View = 0
I suggested that approach because I suspected frmStatsCorr's Form_Load may trigger the 2501 error when it closes itself. But I'm not certain that's the cause of the error and I'm not motivated enough to set up a test.
If you still have 2501 errors with the approach I suggested, there are two other possible causes I've encountered:
corruption
broken references

What are some good patterns for VBA error handling? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
The community reviewed whether to reopen this question 6 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
What are some good patterns for error handling in VBA?
In particular, what should I do in this situation:
... some code ...
... some code where an error might occur ...
... some code ...
... some other code where a different error might occur ...
... some other code ...
... some code that must always be run (like a finally block) ...
I want to handle both errors, and resume execution after the code where the error may occur. Also, the finally code at the end must always run - no matter what exceptions are thrown earlier. How can I achieve this outcome?
Error Handling in VBA
On Error Goto ErrorHandlerLabel
Resume (Next | ErrorHandlerLabel)
On Error Goto 0 (disables current error handler)
Err object
The Err object's properties are normally reset to a zero or a zero-length string in the error handling routine, but it can also be done explicitly with Err.Clear.
Errors in the error handling routine are terminating.
The range 513-65535 is available for user errors.
For custom class errors, you add vbObjectError to the error number.
See the Microsoft documentation about Err.Raise and the list of error numbers.
For not implemented interface members in a derived class, you should use the constant E_NOTIMPL = &H80004001.
Option Explicit
Sub HandleError()
Dim a As Integer
On Error GoTo errMyErrorHandler
a = 7 / 0
On Error GoTo 0
Debug.Print "This line won't be executed."
DoCleanUp:
a = 0
Exit Sub
errMyErrorHandler:
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub
Sub RaiseAndHandleError()
On Error GoTo errMyErrorHandler
' The range 513-65535 is available for user errors.
' For class errors, you add vbObjectError to the error number.
Err.Raise vbObjectError + 513, "Module1::Test()", "My custom error."
On Error GoTo 0
Debug.Print "This line will be executed."
Exit Sub
errMyErrorHandler:
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Err.Clear
Resume Next
End Sub
Sub FailInErrorHandler()
Dim a As Integer
On Error GoTo errMyErrorHandler
a = 7 / 0
On Error GoTo 0
Debug.Print "This line won't be executed."
DoCleanUp:
a = 0
Exit Sub
errMyErrorHandler:
a = 7 / 0 ' <== Terminating error!
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub
Sub DontDoThis()
' Any error will go unnoticed!
On Error Resume Next
' Some complex code that fails here.
End Sub
Sub DoThisIfYouMust()
On Error Resume Next
' Some code that can fail but you don't care.
On Error GoTo 0
' More code here
End Sub
I would also add:
The global Err object is the closest you have to an exception object
You can effectively "throw an exception" with Err.Raise
And just for fun:
On Error Resume Next is the devil incarnate and to be avoided, as it silently hides errors
So you could do something like this:
Function Errorthingy(pParam)
On Error GoTo HandleErr
' Your code here
ExitHere:
' Your finally code
Exit Function
HandleErr:
Select Case Err.Number
' Different error handling here'
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "ErrorThingy"
End Select
Resume ExitHere
End Function
If you want to bake in custom exceptions (e.g., ones that violate business rules), use the example above, but use the goto to alter the flow of the method as necessary.
Here's my standard implementation. I like the labels to be self-descriptive.
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
Exit Sub
Catch:
'error code: you can get the specific error by checking Err.Number
End Sub
Or, with a Finally block:
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
GoTo Finally
Catch:
'error code
Finally:
'cleanup code
End Sub
Professional Excel Development (PED) has a pretty good error handling scheme. If you're going to spend any time in VBA, it's probably worth getting the book. There are a number of areas where VBA is lacking and this book has good suggestions for managing those areas.
PED describes two error handling methods. The main one is a system where all entry point procedures are subprocedures and all other procedures are functions that return Booleans.
The entry point procedure use On Error statements to capture errors pretty much as designed. The non-entry point procedures return True if there were no errors and False if there were errors. Non-entry point procedures also use On Error.
Both types of procedures use a central error handling procedure to keep the error in state and to log the error.
Also relevant to the discussion is the relatively unknown Erl function. If you have numeric labels within your code procedure, e.g.,
Sub AAA()
On Error Goto ErrorHandler
1000:
' code
1100:
' more code
1200:
' even more code that causes an error
1300:
' yet more code
9999: ' end of main part of procedure
ErrorHandler:
If Err.Number <> 0 Then
Debug.Print "Error: " + CStr(Err.Number), Err.Descrption, _
"Last Successful Line: " + CStr(Erl)
End If
End Sub
The Erl function returns the most recently encountered numberic line label. In the example above, if a run-time error occurs after label 1200: but before 1300:, the Erl function will return 1200, since that is most recently successfully encountered line label. I find it to be a good practice to put a line label immediately above your error handling block. I typically use 9999 to indicate that the main part of the procedure ran to its expected conclusion.
Notes:
Line labels must be positive integers -- a label like MadeItHere: isn't recogonized by Erl.
Line labels are completely unrelated to the actual line numbers of a VBIDE CodeModule. You can use any positive numbers you want, in any order you want. In the example above, there are only 25 or so lines of code, but the line label numbers begin at 1000. There is no relationship between editor line numbers and line label numbers used with Erl.
Line label numbers need not be in any particular order, although if they are not in ascending, top-down order, the efficacy and benefit of Erl is greatly diminished, but Erl will still report the correct number.
Line labels are specific to the procedure in which they appear. If procedure ProcA calls procedure ProcB and an error occurs in ProcB that passes control back to ProcA, Erl (in ProcA) will return the most recently encounterd line label number in ProcA before it calls ProcB. From within ProcA, you cannot get the line label numbers that might appear in ProcB.
Use care when putting line number labels within a loop. For example,
For X = 1 To 100
500:
' some code that causes an error
600:
Next X
If the code following line label 500 but before 600 causes an error, and that error arises on the 20th iteration of the loop, Erl will return 500, even though 600 has been encountered successfully in the previous 19 iterations of the loop.
Proper placement of line labels within the procedure is critical to using the Erl function to get truly meaningful information.
There are any number of free utilities on the Internet that will insert numeric line label in a procedure automatically, so you have fine-grained error information while developing and debugging, and then remove those labels once code goes live.
If your code displays error information to the end user if an unexpected error occurs, providing the value from Erl in that information can make finding and fixing the problem vastly simpler than if value of Erl is not reported.
The code below shows an alternative that ensures there is only one exit point for the sub/function.
function something() as ResultType
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim res as ResultType
' Partial declaration block shown
on error goto errHandler
res.errMsg = ""
do ' Dummy loop
Set conn = initDB(databaseFilename)
conn.BeginTrans
Set rstCust = New ADODB.Recordset
sql = "SELECT cust_name FROM customers"
rstCust.Open sql, conn, adOpenKeyset, adLockOptimistic
....
....
if needToExit then
res.errMsg = "Couldn't stand the weather"
exit do
end if
....
....
if gotToGetOutOfHere then
exit do
end if
....
loop until true
' End of code. Single exit point for all above code
' Think of this as the 'exit' handler that
' handles both error and normal exits
errHandler:
if Err.number <> 0 then
res.errMsg = Err.description
end if
If Not rst Is Nothing Then
If rst.State = adStateOpen Then
rst.Close
End If
Set rst = Nothing
End If
If Not conn Is Nothing Then
If res.errMsg = "" Then
conn.CommitTrans
Else
conn.RollbackTrans
End If
conn.Close
Set conn = Nothing
End If
something = res
end function
I use a piece of code that I developed myself and it is pretty good for my code:
In the beginning of the function or sub, I define:
On error Goto ErrorCatcher:
And then, I handle the possible errors
ErrorCatcher:
Select Case Err.Number
Case 0 ' Exit the code when no error was raised
On Error GoTo 0
Exit Function
Case 1 ' Error on definition of object
'do stuff
Case... ' A little description here
' Do stuff
Case Else
Debug.Print "###ERROR"
Debug.Print " • Number :", Err.Number
Debug.Print " • Descrip :", Err.Description
Debug.Print " • Source :", Err.Source
Debug.Print " • HelpCont:", Err.HelpContext
Debug.Print " • LastDLL :", Err.LastDllError
Stop
Err.Clear
Resume
End Select
Here's a pretty decent pattern.
For debugging: When an error is raised, hit Ctrl + Break (or Ctrl + Pause), drag the break marker (or whatever it's called) down to the Resume line, hit F8 and you'll step to the line that "threw" the error.
The ExitHandler is your "Finally".
The hourglass will be killed every time. The status bar text will be cleared every time.
Public Sub ErrorHandlerExample()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
On Error GoTo ErrHandler
Dim varRetVal As Variant
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("SomeTable", dbOpenDynaset, dbSeeChanges + dbFailOnError)
Call DoCmd.Hourglass(True)
' Do something with the RecordSet and close it.
Call DoCmd.Hourglass(False)
ExitHandler:
Set rst = Nothing
Set dbs = Nothing
Exit Sub
ErrHandler:
Call DoCmd.Hourglass(False)
Call DoCmd.SetWarnings(True)
varRetVal = SysCmd(acSysCmdClearStatus)
Dim errX As DAO.Error
If Errors.Count > 1 Then
For Each errX In DAO.Errors
MsgBox "ODBC Error " & errX.Number & vbCrLf & errX.Description
Next errX
Else
MsgBox "VBA Error " & Err.Number & ": " & vbCrLf & Err.Description & vbCrLf & "In: Form_MainForm", vbCritical
End If
Resume ExitHandler
Resume
End Sub
Select Case Err.Number
Case 3326 'This Recordset is not updateable
'Do something about it. Or not...
Case Else
MsgBox "VBA Error " & Err.Number & ": " & vbCrLf & Err.Description & vbCrLf & "In: Form_MainForm", vbCritical
End Select
It also traps for both DAO and VBA errors. You can put a Select Case in the VBA error section if you want to trap for specific Err numbers.
Select Case Err.Number
Case 3326 'This Recordset is not updateable
'Do something about it. Or not...
Case Else
MsgBox "VBA Error " & Err.Number & ": " & vbCrLf & Err.Description & vbCrLf & "In: Form_MainForm", vbCritical
End Select
I find the following to work best, called the central error handling approach.
Benefits
You have two modes of running your application: Debug and Production. In the Debug mode, the code will stop at any unexpected error and allow you to debug easily by jumping to the line where it occurred by pressing F8 twice. In the Production mode, a meaningful error message will get displayed to the user.
You can throw intentional errors like this, which will stop execution of the code with a message to the user:
Err.Raise vbObjectError, gsNO_DEBUG, "Some meaningful error message to the user"
Err.Raise vbObjectError, gsUSER_MESSAGE, "Some meaningful non-error message to the user"
'Or to exit in the middle of a call stack without a message:
Err.Raise vbObjectError, gsSILENT
Implementation
You need to "wrap" all subroutines and functions with any significant amount of code with the following headers and footers, making sure to specify ehCallTypeEntryPoint in all your entry points. Note the msModule constant as well, which needs to be put in all modules.
Option Explicit
Const msModule As String = "<Your Module Name>"
' This is an entry point
Public Sub AnEntryPoint()
Const sSOURCE As String = "AnEntryPoint"
On Error GoTo ErrorHandler
'Your code
ErrorExit:
Exit Sub
ErrorHandler:
If CentralErrorHandler(Err, ThisWorkbook, msModule, sSOURCE, ehCallTypeEntryPoint) Then
Stop
Resume
Else
Resume ErrorExit
End If
End Sub
' This is any other subroutine or function that isn't an entry point
Sub AnyOtherSub()
Const sSOURCE As String = "AnyOtherSub"
On Error GoTo ErrorHandler
'Your code
ErrorExit:
Exit Sub
ErrorHandler:
If CentralErrorHandler(Err, ThisWorkbook, msModule, sSOURCE) Then
Stop
Resume
Else
Resume ErrorExit
End If
End Sub
The contents of the central error handler module is the following:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Comments: Error handler code.
'
' Run SetDebugMode True to use debug mode (Dev mode)
' It will be False by default (Production mode)
'
' Author: Igor Popov
' Date: 13 Feb 2014
' Licence: MIT
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Option Explicit
Option Private Module
Private Const msModule As String = "MErrorHandler"
Public Const gsAPP_NAME As String = "<You Application Name>"
Public Const gsSILENT As String = "UserCancel" 'A silent error is when the user aborts an action, no message should be displayed
Public Const gsNO_DEBUG As String = "NoDebug" 'This type of error will display a specific message to the user in situation of an expected (provided-for) error.
Public Const gsUSER_MESSAGE As String = "UserMessage" 'Use this type of error to display an information message to the user
Private Const msDEBUG_MODE_COMPANY = "<Your Company>"
Private Const msDEBUG_MODE_SECTION = "<Your Team>"
Private Const msDEBUG_MODE_VALUE = "DEBUG_MODE"
Public Enum ECallType
ehCallTypeRegular = 0
ehCallTypeEntryPoint
End Enum
Public Function DebugMode() As Boolean
DebugMode = CBool(GetSetting(msDEBUG_MODE_COMPANY, msDEBUG_MODE_SECTION, msDEBUG_MODE_VALUE, 0))
End Function
Public Sub SetDebugMode(Optional bMode As Boolean = True)
SaveSetting msDEBUG_MODE_COMPANY, msDEBUG_MODE_SECTION, msDEBUG_MODE_VALUE, IIf(bMode, 1, 0)
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Comments: The central error handler for all functions
' Displays errors to the user at the entry point level, or, if we're below the entry point, rethrows it upwards until the entry point is reached
'
' Returns True to stop and debug unexpected errors in debug mode.
'
' The function can be enhanced to log errors.
'
' Date Developer TDID Comment
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 13 Feb 2014 Igor Popov Created
Public Function CentralErrorHandler(ErrObj As ErrObject, Wbk As Workbook, ByVal sModule As String, ByVal sSOURCE As String, _
Optional enCallType As ECallType = ehCallTypeRegular, Optional ByVal bRethrowError As Boolean = True) As Boolean
Static ssModule As String, ssSource As String
If Len(ssModule) = 0 And Len(ssSource) = 0 Then
'Remember the module and the source of the first call to CentralErrorHandler
ssModule = sModule
ssSource = sSOURCE
End If
CentralErrorHandler = DebugMode And ErrObj.Source <> gsNO_DEBUG And ErrObj.Source <> gsUSER_MESSAGE And ErrObj.Source <> gsSILENT
If CentralErrorHandler Then
'If it's an unexpected error and we're going to stop in the debug mode, just write the error message to the immediate window for debugging
Debug.Print "#Err: " & Err.Description
ElseIf enCallType = ehCallTypeEntryPoint Then
'If we have reached the entry point and it's not a silent error, display the message to the user in an error box
If ErrObj.Source <> gsSILENT Then
Dim sMsg As String: sMsg = ErrObj.Description
If ErrObj.Source <> gsNO_DEBUG And ErrObj.Source <> gsUSER_MESSAGE Then sMsg = "Unexpected VBA error in workbook '" & Wbk.Name & "', module '" & ssModule & "', call '" & ssSource & "':" & vbCrLf & vbCrLf & sMsg
MsgBox sMsg, vbOKOnly + IIf(ErrObj.Source = gsUSER_MESSAGE, vbInformation, vbCritical), gsAPP_NAME
End If
ElseIf bRethrowError Then
'Rethrow the error to the next level up if bRethrowError is True (by Default).
'Otherwise, do nothing as the calling function must be having special logic for handling errors.
Err.Raise ErrObj.Number, ErrObj.Source, ErrObj.Description
End If
End Function
To set yourself in the Debug mode, run the following in the Immediate window:
SetDebugMode True
My personal view on a statement made in previous answers:
And just for fun:
On Error Resume Next is the devil incarnate and to be avoided, as it silently hides errors.
I'm using the On Error Resume Next on procedures where I don't want an error to stop my work and where any statement does not depend on the result of the previous statements.
When I'm doing this I add a global variable debugModeOn and I set it to True. Then I use it this way:
If not debugModeOn Then On Error Resume Next
When I deliver my work, I set the variable to false, thus hiding the errors only to the user and showing them during testing.
Also using it when doing something that may fail like calling the DataBodyRange of a ListObject that may be empty:
On Error Resume Next
Sheet1.ListObjects(1).DataBodyRange.Delete
On Error Goto 0
Instead of:
If Sheet1.ListObjects(1).ListRows.Count > 0 Then
Sheet1.ListObjects(1).DataBodyRange.Delete
End If
Or checking existence of an item in a collection:
On Error Resume Next
Err.Clear
Set auxiliarVar = collection(key)
' Check existence (if you try to retrieve a nonexistent key you get error number 5)
exists = (Err.Number <> 5)
Beware of the elephant trap:
I saw no mention of this in this discussion. Access 2010
How ACCESS/VBA handles errors in CLASS objects is determined by a configurable option:
VBA Code Editor → Tools → Options → General → Error Trapping:
Error-handling has always been a bother. I've experimented with various techniques. Here's my solution.
This approach brings together my preferred methods on this SO page, plus a few of my own techniques.
The question asker mentions only the simple case -- a single procedure. I also cover sub-procedures, custom errors, logging, error-related processing, and other error-related topics.
No error-handling
The simplest case: Don't assume you always need handling. Procedures which are never going to error out don't need error-handling.
Ignored Errors
It's acceptable to simply ignore some errors. This is perfectly acceptable example of an ignored error, because you know there's no other error that can reasonably occur on that statement.
...
On Error Resume Next
Set bkCars = Workbooks("Cars.xlsx")
On Error GoTo 0
If (bkCars Is Nothing) Then MsgBox "Cars workbook isn't open."
Set bkCars = Workbooks("Wheelbarrows.xlsx")
...
I've never heard of any other error ever happening on that statement. Use your judgement. Ignore extremists. VBA is supposed to be easy. On Error Resume Next isn't "the Devil incarnate"; it's one way to implement Try..Catch in VBA. For more examples, see Jordi's answer.
Unhandled Errors
The remainder of this answer is about unhandled errors. An unhandled error is an unexpected error which breaks your program.
Handler
Here's my basic handler:
Sub Main()
On Error GoTo HANDLER
Dim x As Long
x = "hi"
HANDLER:
' cleanup
x = 0
' error-handler
If (Err = 0) Then Exit Sub
MsgBox Error
End Sub
Flow-through: Inspired by #NickD and others here, it completely eliminates "Exit Sub" and "Resume" from your code. Code flows in one direction, instead of jumping around. There's a single exit point in the procedure. All are important, if you like less typing, less code, and less spaghetti.
*Cleanup: This approach ensures the same cleanup code runs whether there is or isn't an error. Error and non-error conditions share the same cleanup code. Straightforward pattern handles a wide variety of scenarios regarding cleanup and custom-handling.
Convenience
Make your life easier.
Function IsEr() As Boolean
IsEr = (Err <> 0)
' or IsEr = CBool(Err)
End Function
Special Handlers
The basic style can handle more complex cases. For example, you can insert handling or cleanup for specific errors.
...
HANDLER:
If Not IsEr Then Exit Sub
If (Err = 11) Then Call_TheBatphone
MsgBox Error
End Sub
Procedure Calls, No Cleanup
A called procedure which doesn't have any special cleanup code doesn't need any error-code. It's errors, and those of it's sub-procedures, will automatically bubble up to the entry-procedure. You can have cleanup-code at each sub.
Sub Main()
On Error GoTo HANDLER
Sub_1
HANDLER:
If Not IsEr Then Exit Sub
MsgBox Error
End Sub
Sub Sub_1()
Dim x
x = 5/0 <.. will jump to Main HANDLER
End Sub
Procedure Calls, Cleanup
However, a sub-procedure which must always run cleanup-code (even in case of an error) needs a bit of extra help. The sub's error-handler resets the error-event, so the error must be retriggered with Err.Raise.
This means your handler for subs must be different than the handler for the kickoff-procedure (aka "entry-point", meaning the first procedure that runs at the beginning of the roundtrip code-loop).
Sub-handlers shouldn't show any message boxes or do any logging -- that should remain with the Main handler. Sub handlers should only be used for special cleanup, special processing, and to append extra error-info to the error object.
Sub Main()
On Error GoTo HANDLER
Sub_1
HANDLER:
If Not IsEr Then Exit Sub
MsgBox Error
End Sub
Sub Sub_1()
On Error GoTo HANDLER
Dim x
x = 5/0
' More processing here
HANDLER:
If Not IsEr Then Exit Sub
Err.Raise Err.Number, Err.Source, Err.Description & vbNewline & "Some problem with divisor"
End Sub
Run
Beware: any procedure executed with the Run statement requires special handling. If you raise an error within the procedure, the error will not bubble up to the entry procedure, and whatever into the Raise puts into the Err will be lost when execution returns to the caller. Therefore, you need to create a workaround. My workaround is to put Err.Number into a global variable, and then on return from the Run, check that variable.
Public lErr As Long
Sub Main()
On Error GoTo HANDLER
Run "Sub_1"
If (lErr <> 0) then Err.Raise lErr
Dim x
x = 5
HANDLER:
If Not IsEr Then Exit Sub
MsgBox Error
End Sub
Sub Sub_1()
On Error Goto HANDLER
Dim x
' will NOT jump to Main HANDLER, since Run
x = 5/0
HANDLER:
If (Err <> 0) Then lErr = Err
End Sub
Alerts
If your intention is produce professional code, then you must communicate all unexpected errors appropriately to the user, as shown above. You never want users to see a "Debug" button or find themselves dropped into VBA.
Centralized Handling
The next evolution is centralized handling. This gives you a really quick and easy way to replicate your perfect error-handling everywhere. As mentioned by #igorsp7, centralized handling makes it simpler and easier to implement consistent, reliable error-handling everywhere. It makes it easy to reuse complex handler logic. It is so easy and simple to just place ErrorHandler at the bottom of every procedure. Reminder: Err is a global object, so there's no need to pass it around as an argument.
Sub Main()
On Error GoTo HANDLER
Sub_1
HANDLER:
MainCleanup
ErrorHandler_Entry
End Sub
Sub Sub_1()
On Error GoTo HANDLER
Dim x
x = 5/0
HANDLER:
SubCleanup
ErrorHandler_Sub
End Sub
Sub ErrorHandler_Entry()
If Not IsEr Then Exit Sub
' log error to a file for developer to inspect.
Log_Error_To_File
' Then alert user. InputBox provides simple way to let users copy with mouse
InputBox "Sorry, something went haywire. Please inform the developer or owner of this application.", _
"Robot Not Working", Err.Number & vbNewLine & Err.Source & vbNewLine & Err.Description
End Sub
Private Sub ErrorHandler_Sub()
If Not IsEr Then Exit Sub
' bubble up the error to the next caller
Err.Raise Err.Number, Err.Source, Err.Description
End Sub
Custom Errors
Numbering
Use = vbObjectError + 514 for your first one, as 1 to 513 are reserved for native VB errors. I'm still researching custom error numbering. There's a lot of conflicting information. It may be simply
Native errors are positive integers, to 65535?
Custom errors are negative integers, 0 to -2,000,000,000?
But I don't know yet if that's correct! Your error handlers will work even if you use native error numbers. However, if your error handling is based on whether it's a native vs custom error, or if your application is reporting the error to a developer, then to avoid confusion or more bugs, the best practice is to not reuse native numbers.
Syntax
Enum CustomError
UserPause = vbObjectError + 514
UserTerminate
End Enum
Function CustomErr()as Boolean
CustomErr = (Err >= 514)
End Function
Sub Test
On Error Goto HANDLER
Err.Raise CustomError.UserPause
HANDLER:
Cleanup
If CustomErr Then Handle_CustomError
End Sub
Sub Handle_CustomError()
Select Case Err
Case UserPause
MsgBox "Paused"
Resume Next
Case UserTerminate
SpecialProcessing
MsgBox "Terminated"
End
End Select
End Sub
Error Categories:
You may want custom errors in an addin, an application workbook, and a data workbook. You should reserve a range of allowed error numbers for each type. Then your handlers can determine the source of the error by its number. This enum uses the starting number for each range.
Enum AppError
UserPause = vbObjectError + 514
UserTerminate
End Enum
Enum AddinError
LoadFail = vbObjectError + 1000
End Enum
Enum DataError
DatabaseLocked = vbObjectError + 1500
End Enum
Enum ErrorType
VB
App
Addin
Data
End Enum
Function Get_ErrorCategory() As ErrorType
If (Err < 514) Then
Get_ErrorCategory = VB
ElseIf (Err <= 1000) Then
Get_ErrorCategory = App
ElseIf (Err <= 1500) Then
Get_ErrorCategory = Addin
Else
Get_ErrorCategory = Data
End If
End Function
Sub ErrorHandler_Entry(Optional sInfo As String)
If Not IsEr Then Exit Sub
Select Case Get_ErrorCategory
Case VB
InputBox "Sorry, something went haywire. Please inform the developer or owner of this application.", _
"Robot Not Working", Err.Number & vbNewLine & Err.Source & vbNewLine & Err.Description & vbNewLine & sInfo
Case Addin
Log_Error_To_File
Case Data
' do nothing
End Select
End Sub
Developer Mode
As developer, you'll want to debug unhandled errors, instead of getting friendly messages. So you want to temporarily disable your handler when you're in development. That's conveniently done by manually setting a "Debug" state someplace. There are a couple of ways to do it:
Custom "ExecMode":
Get_DebugMode is a function that you need to write, which pulls your Debug mode from wherever you stored it. Can be stored in an Excel defined-name, a module constant, a worksheet cell -- whatever you prefer.
...
If Not Get_DebugMode Then _
On Error GoTo HANDLER
...
Conditional Compilation Arguments:
This needs to be applied in the VB IDE.
...
#If Not DEBUGMODE Then _
On Error GoTo HANDLER
...
Changing code behavior at compile time