Question

I have a simple excel function that connects to a db and retrieves some data and populates a worksheet. The function calls another function to make the db connection and return the query results. How do I exit the calling function if there is an error connecting to the database? This is what my function looks like that connects to the DB. If there is an error connecting to the DB, the messagebox is displayed but then processing resumes in the calling function and then I get an ugly "END or DEBUG" message box...which I am trying to avoid.

Public Function QueryDB(sQuery As String)

On Error GoTo ErrorHandler

... Connect to database and get data

ErrorHandler:
... Display a messagebox telling the user there is an error

'Resume Next
Exit Function

End Function
Was it helpful?

Solution

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

OTHER TIPS

It can be done using Global level variable as below:

Public dbError as Integer

Function ConnectToDb as Integer
   On Error GoTo err_Connection
   'Asume connection to DB failure
   err_Connection:
   MsgBox "Connection failed to database !! ", vbOKOnly + vbExclamation
   dbError = -500 'Any number
      Exit Function
End Function

Sub MainSub 
'Call function
ConnectToDb
 If dbError = -500 Then
    Exit Sub
 End If
End Sub

Use "exit sub" command wherever necessary. as you did n't shared your subroutine/function, I cannot point out where it needs to be given. add "exit sub" according to your logic.

Regards,

Dominic

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top