Debug.Print “The Fine Print”

If you have used VBA for more than just recording Macros in Excel, you probably know about Debug.Print, so I won’t go into the usual stuff, but rather tell you about some of the lesser known features of Debug.Print.

A) Converting ? to Print

If you are lazy (And it takes a lazy programmer to be a good programmer) then you instead of typing Debug.Print Expression you can simply type ? Expression, and the VBE will convert the ? into Print for you

B) Debug.Print without Newline

If you want to write more than once to the immediate pane without going to the next line, you can end your Print statement with a semicolon ; . You can try it with this code snippet to see how it works:

Private Declare PtrSafe Sub apiSleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)

Public Sub test_print()
   Debug.Print "Test running";
   Dim I As Long
   For I = 1 To 20
      Debug.Print ".";
      apiSleep 100
   Debug.Print "Done"
End Sub

C) Spacing the result by use of ,

Sometimes it can be useful to get a more table like output from your code. If you include a , in your Print statement, it will act as a TAB to indent the next part of your statement. This works well for strings of fairly equal length, but can look weird otherwise. Take this simple code snippet to list the creation date for all forms in the database:

Private Sub space_print()
   Debug.Print "Starting form date listing"
   Dim ao As AccessObject
   For Each ao In CurrentProject.AllForms
      Debug.Print ao.Name, Format(ao.DateCreated, "yyyymmdd")
End Sub

As you can see from the screenshot below, the time portion of the result is somewhat aligned (Remember what I said about strings of different lengths?)

Tagged with: , ,
2 comments on “Debug.Print “The Fine Print”
  1. bsacheri says:

    D) Spacing with fixed columns using Tab(). This makes example C look prettier.

    If you know your Name field text length can vary between 1 and 30 characters use the Tab() function with Debug.Print to make the text start at a specific column position. You have to use the semicolon ; instead of the comma in order for this to work.

    Modify the code from example C and see the difference.

    Debug.Print ao.Name; Tab(32); Format(ao.DateCreated, “yyyymmdd”)

  2. TheSmileyCoder says:

    Nice, I didn’t know that. Thanks for posting.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.