Debugging VBA Code
As we move on from writing simpler to more complex VBA code, there are times when we need to debug the code and there are multiple variables or pieces of code which we need to keep track of. Below are some of the options available in VBA interface.
There are three windows which can be used while debugging, all of them are placed in View menu in VBA GUI –
- Local Window
- Immediate Window
- Watch Window
In image shown below,you can see these 3 windows in View menu in Visual Basic Editor .
Local window – You can activate this window by navigating to view option as shown in the image above. In this window we can see the values of all the variables in the currently running sub procedure. We can navigate through each line by pressing F8. Once the subroutine ends, all the variables will disappear from the local window. Sometimes when the value of multiple variables changes due to various operations performed on them and we need to verify the final values contained in those variables, then this window turns out to be very useful.
There are scenarios when we are debugging a code which has hundreds of lines, in that case if we get any error [ like Overflow Error] , then we need to modify and test the code, then instead of running the entire code again, we can write the specific line of code in the immediate window and check the results.
For example, we are evaluating a formula and we are not getting the correct values, then we can modify the formula in the immediate window and once the correct results are obtained , we can implement the same in the actual code. Below is the screenshot where you can see results of a formula.
To evaluate the value of a statement we need to add a question mark sign (?) before the statement.
This window is used when we are focused on only few variables. To monitor a variable in watch window, we need to right click on that variable , and click on Add Watch as shown in the screenshot below.
Latest value and the data type of any variable will be showcased in this window. Multiple variables can be added in the watch list.
By using these 3 windows during debugging VBA code, we can easily track the values of different variables.
Post you may like