10

I need to trigger(return) an error event from a VBA function, then the calling function of this function can trigger On Error Go to call. E.g

function Test()
 On Error Go to myError:
       TestErr()
 Exit Function

 myerror:
    Test = "Error Triggered"
End Function

Function TestErr()
    ?? 'How to Trigger error here
End Function

Thank You

3 Answers 3

23

Err.Raise 5, "optional error source" , "optional error description"

MSDN reference http://msdn.microsoft.com/en-us/library/aa164019%28office.10%29.aspx#odc_tentipsvba_topic3

Sign up to request clarification or add additional context in comments.

3 Comments

I think there should be two commas after the '5'. The second argument is for Source, the third for Description.
According to the referenced page it should be: Err.Raise vbObjectError + 5, "optional error source" , "optional error description". But either way I don't see my custom error on the worksheet. I used this to raise an error when the user passes incompatible arguments to a custom function. The cell just reports "A value used in the formula is of the wrong data type" if I enter values that invoke the 'Err.Raise' code. Neither source nor description are visible. Not sure I see the point. 1/0 does the same.
@bielawski The two parameters are used with the error handler in VBA, via Err.Source and Err.Description. Using the built in error code of 5 would be appropriate if the error was "Invalid procedure call or argument" (which is the Err.Description that goes with Err.Number 5).
9

Dirty way: 1 / 0

2 Comments

Haha!! I initially thought about this when I saw the question
The message will be unhelpful.
4

Not what you asked, but note that if you want to return an error to a cell from a UDF, use CVErr. Like

Test = CVErr(xlErrNA)

to return #NA

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.