Debug is the VBA application object which is used for debugging VBA code.There are two methods which are applicable for this object –
(1) Debug.Print – While we are debugging the VBA code, it will print the value of a variable or a string. The output of this statement will be shown in the immediate window.It is a good practice to include this statement in the sub routine at the location in code where we want to track the value of a variable, or any particular statement. After debugging, we can comment/omit it out from the code.
Sub DemoNew() Dim MyVar As Variant MyVar = 122 Debug.Print "Current Value of the variable is " & MyVar End Sub
When we debug the above code by using F8 key, we can see the output is shown in the immediate window.
(2) Debug.Assert – It will stop the code when the value in the expression turns out to be false.If the condition is evaluated as true, then the next line of code will be executed, otherwise code will stop at the line where Debug.Assert is mentioned. Post which, we can debug the code using F8.
Below shown is the syntax of assert method-
Sub DebugAssert() Dim MyVar As Variant MyVar = 150 Debug.Assert MyVar > 200 MyVar = MyVar * 10 End Sub
In the code above, when the code execution will reach the line with Debug.Assert statement,it will check if the value of variable MyVar [i.e. 150] is greater than 200 , which is false in this case, it will bring the code in break mode. It will do nothing, but simply stop the code, if debug.assert’s results are false. Post which, we can use F8 to debug the code further, or we can find the root cause, which made this Boolean expression as false.
Post you may like