Use debug.print to trail what is happening

When you want to figure out why your program is not behaving as expected you want to see the values of the relevant variables. The VBA editor has several useful tools.

Write trail info using Debug.Print

Debug.Print writes info to the Immediate Window. It has the advantages over using a message box in your code in 1. You don't have to click the Ok button all the time and 2. it gives you a log of the returned values so you don't have to remember or write down yourself.


    Debug.Print "FileName= " & strFileName
Debug.Print writes values to Immediate Window

You can insert the Debug.Print easily from the Code VBA menu: Error » Debug.Print saving you some keystrokes.

The Immediate Window

The Immediate Window is the central place for debugging. You can open it using menu: View » Immediate Window (Ctrl-G)

Other ways to use the Immediate Window when debugging are (note that you will have to strategically set breakpoints in your code first):

  • Request or change(!) the values of variables during a Debug session.
    ?strFile
    strName = "John"
    The first asks the current value for variable strFile, the second sets the value
  • Start a procedure or function: type the name of the procedure and press [Enter].
    Instead of typing you can also in Code VBA Code Explorer right-click the procedure and select Immediate.