Return to VBA Code Examples

VBA Throw / Raise Error – Err.Raise – Custom Error Msg

This tutorial will demonstrate how to raise a custom error in VBA.

Custom errors can be created in VBA code when the programmer wants to return a specific message to the user, rather than relying on the default error message box that will pop up, or when the user actually wants to show a custom error if a certain value is inputted into a variable or variables in the code.

Creating a Simple Custom Error Message

The Err. Raise method allows us to customize the error number and the error description in our code.

We need to raise a custom error number that we have documented ourself.  We use the constant vbObjectError in addition to our custom number to ensure that we do not end up using any of the error numbers that are reserved by VBA for internal use.

Creating a Custom Error Message Depending on User Input

We can raise an error that will return a specific message – depending on what information is entered into the code.

First, we can create this function:

Then we can create this code to test the function:

As the difference between the numbers 49 and 100 is greater than 50, the custom error description returned will be “The difference is too large“.

If we were to amend this line in the code:

Then the custom error description returned would be “The difference is too small”.

If we were then to amend the line of code to read:

Then no error would be returned by the function TestCustomError.

Replacing the Custom Excel Error Message with a Custom Message

You can use existing Excel error to create your own custom message to return to the user.

Take the example of the code below:

This will result in the following error being returned:

VBA Err Raise Msg Box

However, we can customize the message “Division by zero” by altering the code as per the example below:

VBA Err Raise Custom MsgBox

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as

Learn More!