1. Home
  2. Computing & Technology
  3. Visual Basic

Learn VBA Macro Coding with Word 2007 - A "From the Ground Up" Tutorial
Take It One Step At A Time!

By Dan Mabbutt, About.com

May 24 2008

Back in the 'good old days' (They were really 'bad old days'. Trust me on that!), programmers used to spend hours and hours 'bench checking' their programs before ever trying them out on a real computer. The primary method was to step through the program one statement at a time to make sure it did what you wanted it to do.

Stepping through the code

In the 'good old days' we had to imagine what the computer would actually do by just looking at the program statements but there are much better methods available today. We do basically the same thing now but like so many things, we use the computer itself to do the hard and boring part. We call this process, "stepping through the code".

The debug options that are available to you can be found on the Debug menu after starting the Visual Basic editor under the Developer tab. The first four menu items are the ones you will use most often. The words Into, Over and Out refer to the current running procedure. So, for example, when you press F8 (Step Into), Visual Basic starts your macro, goes to the very first statement (which is indicated by the arrow and the highlighting), and then stops and waits for more instructions. The other 'Step' options are simply alternative ways to tell VB where to stop and wait. And there are more ways, too. To read more about this, start your VB Help system and search for "Trace Code Execution".

The main reason for using this technique is to see whether VB is executing loops, conditional statements (If statments, for example) and subroutine calls when you expect it to. Up to this point, we haven't seen any because most of the code has simply been objects. So to illustrate program stepping, let's code basically the same thing that the macro recorder did for us ... but do it with conditional logic and loops.

The FormLetter macro searches for a particular sequence of characters - (1) and (2) - and replaces them with a different text string. Here's some code that will do that for (1).

Again, statement continuation has been used to keep the lines short for the web page. The converted text can be viewed by displaying the variable NewDoc. This isn't "production quality" code. The only goal is to compare the action of a looping construct to Word objects.

Set myDoc = _
   Word.ActiveDocument.Content.Words
Dim NewDoc As String
Dim PFlag As Integer
PFlag = 0
For Each Searchword In myDoc
   If Searchword = "(" _
      Then PFlag = 1
   If Searchword = "1" _
      And PFlag = 1 _
      Then PFlag = 2
   If Left$(Searchword, 1) = ")" _
      And PFlag = 2 Then
      NewDoc = _
      Left$(NewDoc, Len(NewDoc) - 2)
      NewDoc = NewDoc & "Mr. Publisher Dude"
   Else
      NewDoc = NewDoc & Searchword
   End If
Next Searchword

This does approximately the same thing as this macro recorder code:

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "(1)"
   .Replacement.Text = _
      "Mr. Publisher Dude"
   .Forward = True
   .Wrap = wdFindContinue
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False
End With
Selection.Find.Execute
With Selection
   If .Find.Forward = True Then
      .Collapse Direction:=wdCollapseStart
   Else
      .Collapse Direction:=wdCollapseEnd
   End If
   .Find.Execute Replace:=wdReplaceOne
   If .Find.Forward = True Then
      .Collapse Direction:=wdCollapseEnd
   Else
      .Collapse Direction:=wdCollapseStart
   End If
   .Find.Execute
End With

In defense of the macro recorder code ... which may look more difficult:

  • It's conservative because it takes into account a lot of possible complications that just don't happen normally. A lot of the macro code could be deleted and it would work about the same way.
  • Because it mainly executes just once to do it's job (rather than looping), it will run faster and more efficiently in nearly all cases and especially in larger text documents. Remember, the Microsoft programmers who wrote the objects that are really doing the work were really great programmers and they did a really great job. The objects let you take advantage of their expertise.
  • The looping code requires some confusing objects too! You just can't get away from 'em so you might as well learn to use 'em!

To see for yourself, step through the code in the Visual Basic editor.

To really understand what the program does, however, you also have to know what information is stored in all of the variables. To examine variables, you need the Immediate and Watch windows. You can find menu commands to show those windows under the View menu item.

Here's the Immediate window showing the value of PFlag inside one of the loops. Check out the Debug object and the Watch and Immediate windows in the VB Help system for more.

Although a lot of things could improve the FormLetter macro, probably the most important missing element is that in order to change anything, you have to change the macro source code! This is just not satisfactory! What the program needs more than anything else is a way to specify that information before it runs.

Part 4 of the tutorial will go into how things like this are added to a VB program in detail. In Part 4, we go well beyond the macro recorder. If any of you have worked with the full VB 6 development system, you'll find the techniques in Part 4 are more what you have seen before.

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Learn VB 6
  5. Learn VBA
  6. Learn VBA Macro Coding with Word 2007 - A "From the Ground Up" Tutorial

©2009 About.com, a part of The New York Times Company.

All rights reserved.