Whenever you create a line of code you have to be aware of the potential of errors frustrating the end user of your product. This post will provide some guidance on how to deal with errors when developing subroutines for Excel VBA.
The Product
Our subroutine is a currency convertor. It specifically converts Thai Baht to US Dollars. Below is the code.

Here is what this code does.
- Line 1 declares sub along with its name
- Line 2 Declare variable we will need
- Line 3 will cause a box to appear that will ask the user to input the amount of Baht to convert
- Line 4 indicates the formula for conversion and the output
It is possible to run this code for the developer. However, this is not for a developer but for a user who may not be familiar with VBA coding. Therefore, we need to have a way to run this subroutine from the Excel spreadsheet.
To run this subroutine from the Worksheet we will create a button. This can be done by clicking
developers-> Insert->Button

Once the button is create Excel will ask you which macro to assign to it. Simply click on the macro that has the same name as the subroutine as shown below.

Implementation
If the user inputs numbers and presses okay the subroutine works fine as you can see below.

Here is the answer below

The Problem
However there are problems if we enter text into our input box or if we click cancel. In either case. We get the following.

Excel takes us to the VBA developer and shows an error message. This can be a serious problem if we want other people to use this subroutine. In order to fix this we will add a few lines to our code as shown below.

Here are the additions
- Line 3 as some code that says “On Error GoTo Here” this tells VBA that when there is any error to jump down to line 7 where the word “Here:” is
- Line 8 is executed whenever there is an error and this brings up the box “There was an error”
- Line 6 makes sure that the error box only occurs when there is an error. If you do not put this Exit Sub code in there the error box will appear every time you run the code whether there is an error or not.
Below is what happens now when there is an error.

Now when there is a problem this is what the end user will see. It’s not clear what the error is but this is less confusing then allowing them to see code and the developer application.
Conclusion
This post provided an example of how to deal with errors when working wit VBA. There is naturally more than one way to handle the problems presented here. However, this is one viable way.
Pingback: Errors & Subroutines in Excel VBA – Wise king