An Example: Debugging the InsertTab Macro

The InsertTab macro in this example is meant to insert a tab character in front of every paragraph in a selection. It uses the CopyBookmark statement to mark the selection with a bookmark called "temp." Then it goes to the start of the selection and moves the insertion point paragraph by paragraph through the document, inserting a tab character in front of each paragraph until it moves outside the area marked with the "temp" bookmark. The macro uses CmpBookmarks("\Sel", "temp") to compare the location of the insertion point (represented by the predefined bookmark " \ Sel") with the "temp" bookmark, which marks the original selection. When the insertion point is no longer within the original selection, the macro should end. Here are the macro instructions:


Sub MAIN
CopyBookmark "\Sel", "temp"                'Copy selection into bookmark
ParaUp                                    'Go to start of first paragraph
While CmpBookmarks("\Sel", "temp") <> 1
    Insert Chr$(9)                        'Insert tab character
    ParaDown                                'Go to next paragraph
Wend
End Sub

When tested, the macro sometimes inserts an additional tab character in front of the first paragraph after the selection. For some reason, the CmpBookmarks("\Sel", "temp") <> 1 condition doesn't always trigger the end of the While¼Wend loop at the right time.

Because the problem has something to do with the CmpBookmarks("\Sel", "temp") <> 1 condition, a good way to start investigating it would be to check the value returned by the CmpBookmarks() function with each iteration of the While¼Wend loop. You can do this by inserting the following instruction inside the While¼Wend loop and then using the Step button to step through the macro:


MsgBox Str$(CmpBookmarks("\Sel", "temp"))

Using this technique, you can discover that when the original selection includes the paragraph mark of the last paragraph in the selection, CmpBookmarks("\Sel", "temp") returns a value of 10 at the beginning of the next paragraph, rather than 1 as expected. When CmpBookmarks() returns a value of 10, it means that the two bookmarks being compared end at the same place but the second bookmark is longer. In this example, that means the insertion point and the "temp" bookmark end at the same place and "temp" marks more text than " \ Sel," which only marks the insertion point.

The corrected macro needs to exit the While¼Wend loop when CmpBookmarks() returns either 10 or 1:


Sub MAIN
CopyBookmark "\Sel", "temp"        'Copy selection into bookmark
ParaUp                            'Go to start of first para in selection
While CmpBookmarks("\Sel", "temp") <> 1 And \
        CmpBookmarks("\Sel", "temp") <> 10
    Insert Chr$(9)
    ParaDown
Wend
End Sub