Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

default value

Status
Not open for further replies.

jmi44

Programmer
Nov 5, 2004
11
CH
I have many calls to different functions that may sometimes provoke errors. In a case of an error, I want them to return a default value. This is possible in the following "spaghetti code" example:

Sub MainTest()
a = 1
b = 0
On Error GoTo DivisionErrorHandler
c = a / b
On Error GoTo 0
MsgBox c

On Error GoTo FontNameErrorHandler
d = He.FontName
On Error GoTo 0
MsgBox d

Exit Sub
DivisionErrorHandler:
c = 0
Resume Next

FontNameErrorHandler:
d = ""
Resume Next
End Sub

Instead of this spaghetti code, I would like to write something like this:

Sub MainTest()
a = 1
b = 0
c = DefaultValue(a / b, 0)
MsgBox c

d = DefaultValue(He.FontName, "")
MsgBox d
End Sub

Is it possible? If yes, how?
 
Don't think so because the error will be raised in the calling routine ... not in the "DefaultValue" function.

You could change your error handling strategy however
Code:
Sub MainTest()
    On Error Resume Next

    a = 1
    b = 0
    c = a / b
    If Err.Number <> 0 Then c = 0
    MsgBox c
    
    Err.Clear
    d = He.FontName
    If Err.Number <> 0 Then d = ""
    MsgBox d

End Sub
 
Or, along with the Resume Next, just set all of the result variables to their default values at the start:

Code:
Sub MainTest()
    On Error Resume Next
    c = 0
    d = ""
.
.
.
 
Thank you Golom and SBerthold. The solution with On Error Resume Next is much better than my "spaghetti code". But it is still four lines of code instead of just one with the desired (but probably impossible) solution.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top