Subroutine are another tool that can be used in Excel VBA for achieving the goals of the creator. Subroutine come from the idea of modular programming in which code that is reused multiple times is created and store in its own separate space and called whenever it is needed. By creating a subroutine separately it does not have to b recreated every time the functions it does are needed.
Many wonder what the difference is between a subroutine and a function. For generally readers this is actually highly esoteric but the main difference is that subroutines do not return a value while functions do. In addition, functions can be used in formulas but subroutines cannot. Right now this difference between functions and subroutines is not important but when programming becomes more complex this difference can be significant.
In the subroutine in this post we are going to make subroutine that calculates the area of a triangle. IN order to achieve this we need the subroutine to do following.
- Ask for the length of the triangle
- Ask for the width of the triangle
- Calculate the area
- Return the answer to the user
The code for this is not as complicated as it seems below is the code.
- In the first line we declare a subroutine use the Sub followed by the name of the subroutine.
- Line 2-3 is where we declare the two variables we will need. Input boxes appear to get this information
- Line 4 we calculate the area
- Line 5 we print the results of area in a message box
To run this subroutine you can press F5 while in the VBA developer. Once this is done you will see the following
First, Excel asks for the length of your triangle. BElow you can see I typed the number 10.
Next, Excel will ask you for the width of your triangle. I put 4
Finally, we get an answer of 20 which is the area of a triangle in this situation.
With a few lines of code we are able to have Excel calculate the area of a triangle. This could have been done with a function or directly on the worksheet. However, if there is a reason you do not want the user to interact with the worksheet or you need to repeat this calculation over and over a subroutine may be more appropriate.