Public Function QueryDB(sQuery As String)
On Error GoTo ErrorHandler
'... Connect to database and get data
' Exit function before the error handler so
' it doesn't get processed every run
Exit Function
ErrorHandler:
' ... Display a messagebox telling the user there is an error
MsgBox "Oops! An error occurred."
End Function
You may want to handle your errors in the calling sub though since errors "bubble up" to the caller. This will cause your macro to debug even though you have an error handler in QueryDB.
Here is an example of how you can handle errors in called functions
Sub Main()
On Error GoTo DBERROR
QueryDB ("Query String")
On Error GoTo 0
Exit Sub
DBERROR:
MsgBox "Oops! Error " & Err.Number & " occurred in " & Err.Source & ".", _
Title:="Error " & Err.Number
End Sub
Public Function QueryDB(sQuery As String)
Err.Raise 5000, "QueryDB", "Error connecting to DB"
End Function