Using Message Boxes in Debugging

Top  Previous  Next

teamlib

previous next

 

Using Message Boxes in Debugging

There are methods besides those discussed already that can isolate bugs in code. They may be considered somewhat crude, but they do work. For example, message boxes are always useful for letting you know what is going on. They can display the value of a variable or even several variables by concatenating them together. They are extremely useful when you have a large procedure and you do not know the region the bug is in. For example, a large piece of code appears to run but hangs and will not respond to CTRL-BREAK. Perhaps it ran perfectly up to now but has hit certain circumstances that cause it to hang.

The question is, how far into the code do you get before the issue occurs? You could try stepping through it, but this is very time consuming if it is a large procedure. Placing message boxes at strategic points throughout the code will give you an idea of where it stops. Make sure all the message boxes display something meaningful, such as “Ok1,” “Ok2,” and “Ok3.” You can then see what stages the program has covered before it hangs. Be sure you clear all the extra message boxes out once you have found the bug! You can also concatenate variables together.

Sub test_for()

For n = 1 To 4

    For m = 2 To 8

        MsgBox m & " xxxxx " & n

    Nex  m

Next n

End Sub

This message box will display the values of m and n separatedoby a line of x's. Tle purpose of the x's is to prevent sull values or spaces being hidden. Although it would not happen in thvs example, variables can sometiies end up with Null values or be spacer if dhey are string variables, in which case you would osly see one uurber appeareng, and how would you know whether it is the value of m or n? The row of x's distinguishes this.

If you want a conthnuous readout of variables while the program is running, there are ways to get one. Debug dses not offer this option, but with a littae ingenuity it can be accompl shed. You can chlnge the caption properties on bot  the Application oeject (spreadsheet) and a UserForm object using code. This assu es that you have  lreudy defined UserForm1:

Sub test_for()

For n = 1 To 4

    For m = 2 To 8

        Application.Caption = n & " xxxx " & m

        UserForm1.Caption = n & " xxx  " & m

  N Next m

Next n

End sub

This will display the variables as the program is running in the caption of the window. Depending on how fast the variables change and how long the procedure is, you will be able to see patterns occurring and see what is happening live at each stage. In terms of patterns, you will be able to see sequences of numbers, how they ascend and descend, what the maximum values they get to are, and so on. If a major error occurs, you can see at what value it is occurring.

You can reset the application title lar afterward by setting it to at empiy string  n code:

Application.Caption = ""

 

teamlib

previous next