Creating Macros In MS WORD

by Don Mankowski

 

One reason that I'm comfortable with computers is this feeling I have that they just ought to be here, ought to have been here all the while.  Even in those dark days of twenty-odd years ago when I didn't have a computer at my disposal all the time, I tried to automate any task that I could.  If I would be recording some data in a similar fashion again, I made up a form and had it copied.  If I knew I'd be writing the same note again, I had copies made up so that I'd just have to enter the new items.  The goal, I suppose, was to never do anything twice; anything that wasn't enjoyable, I mean.

 

Extending MS Word

 

With proper use of special characters and wildcards, Word's Search and Replace function becomes a reasonably good programming language.  Using it judiciously, one can truly rewrite and reshape a document.  At least I find that I don't have to resort to writing a "real" program in (Basic or Fortran or C) quite so often to accomplish these tasks.  But, there are more tricks available to the clever user.  And, you're a clever user, aren't you?

 

The Windows-based versions of Microsoft Word have always provided users with tools to automate repetitive tasks.  The most recent versions, Word 97 and Word 2000 accomplish this by giving the user access to the Visual Basic For Applications (VBA) code that underlies Word itself.  Earlier versions such as Word 95 and Word 6.0 used the WordBasic macro language for the same purpose, and if you're using one of those, this discussion will still be beneficial to you.  The term "macro" refers to a series of commands to be stored and re-used – a program, if you will.

The Process

 

The process is quite simple in conception.  First, you activate macro recording.  Next, you perform the task of interest quite normally.  Finally, you deactivate macro recording and save the instructions.  Thereafter, when you want to perform the same steps in a new context, you simply execute the stored commands. 

 

The only tricky part is where you mentally separate the variable parts of the sequence from the constant ones, but you'll get the hang of that.

 

A Problem

 

What's a common word processing task that you might find yourself performing often?  What about those times when you extract a passage from a web document or a received e-mail.  You will frequently end up with a text file made up of lines, each terminated by a paragraph mark (i.e., "a carriage return" to us old timers).  When you load such crude text into a sophisticated word processing program, things can get funny really fast.  Now, MS Word considers any text string that is terminated by a paragraph mark to be a paragraph and treats it accordingly.  It expects the text within a given paragraph to respect the rules of grammar.  Moreover, Word's too-smart spelling help might capitalize the first letter in each of what it thinks are separate sentences, and complain about their very incompleteness as sentences.  It depends upon how much of its attempts to be helpful you've permitted (the level is adjustable).   If you re-format such text, forcing it into wider or narrower spaces, you'll find that it breaks in all the worst places.

 

To see the paragraph marks, you click on the button with the ¶ symbol on it.  This button is an on-off switch (a "toggle"), and successive clicks turn it on and off.  When this "show-all" mode is active, spaces will show as raised dots, and paragraph marks will show as ¶.  In this mode, your text will probably look something like this: 

 

 

When in the Course of human events, it becomes necessary¶

for one people to dissolve the political bands which have¶

connected them with another, and to assume among the¶

Powers of the earth, the separate and equal station to which¶

the Laws of Nature and of Nature's God entitle them, a¶

decent respect for the opinions of mankind requires that¶

they should declare the causes which impel them to the¶

separation.  

We hold these truths to be self-evident, that all men are¶

created equal, that they are endowed by their Creator with¶

certain unalienable Rights, that among these are Life,  

Liberty and the pursuit of Happiness. That to secure these¶

rights, Governments are instituted among Men, deriving¶

their just powers from the consent of the governed. That¶

whenever any Form of Government becomes destructive of¶

these ends, it is the Right of the People to alter or to abolish¶

it, and to institute new Government, laying its foundation¶

on such principles and organizing its powers in such form,

as to them shall seem most likely to effect their Safety and¶

Happiness.  

 

 

We'd like to strip out these paragraph marks (which I'll call "p-marks" hereafter), so that the words can be rearranged into neat paragraphs, with proper margins and such. 

 

Strategies

 

Your first attempt at solving the problem might be to say, "Darn, this can't be all that difficult.  I'll just tell it to delete all of the paragraph marks."  And you can do just that.  Trouble is, if you succeed in causing Word to remove all the paragraph marks, it will even zap the ones that belong there!  Your whole document - letter, article, story or book, will become one big paragraph. This is one of those things that often get people mad at computers.  They do what you tell them to do.  There's an expression that covers this: "Do what I mean, not what I say!"  Fortunately, you can use Edit | Undo to get back to where you started.  (By Edit | Undo I mean, select the Edit command, and from its menu, select the Undo command.  It's traditional to use the vertical bar to indicate submenus.)

 

Usually you will find that where a double paragraph mark is to be found in your text are the places where you really want a paragraph break.  It's the single p-marks that you want to get rid of.  Still, there's no good, easy way to tell Word to go after the solitary ones and ignore those in pairs, as its logic only "sees" one character at a time.

 

Now, for a big conversion task, and with a "real" programming language at my disposal, I'd probably build in logic to remember the previous character handled, that is, to tell the program "Go ahead and remove p-marks where you find them, but, remember, if you find one and if the very last thing you did was to throw one out, then let this one stand."  That works for human intelligence, and it can be simulated with programming.

 

With sufficient knowledge of VBA, one could develop such a routine that would convert your file in a single pass, but you really can't do it via the simple keyboard entry that we'll be working with just now.  However, there's no good reason not to do it in two (or more) passes.  "Whatever works," as they say. 

 

The revised strategy will be to (1) seek out double p-marks and change them into something distinctive; (2) "remove" any remaining p-marks by changing these to a space or to nothing at all; and then (3) restore the double p-marks.  This works because the double p-marks escaped the second round of changes; the first round rendered them immune.

 

(Do we change them to a space or to nothing?  Activate the p-mark display as we did above.  You might find that if you change the marks to nothing at all, it will cause the last word on one line to get stuck to the first word on the next. "Necessaryfor" and "haveconnected" in our example.  It depends upon how your file was created.  Unless every p-mark is already preceded by a space, you'll have to provide the space yourself in the replacement, which is easy enough.  Trial and error will get you there.)

 

How To …

 

You can perform these three steps once and be done with them.  Then, the next time you're faced with this situation, remember how to do it, and perform the three steps again.  And again the next time. 

 

Face it, either you'll never be doing it again, or you'll do it again until you're sick of it; there's no middle ground.  So, let's prepare for the worst. We'll go through the steps, but we'll ask Word to remember the steps for us, so that it can do all of the work next time.

 

(If you want to follow my instructions as you work, you may want to print a hardcopy of this document, so that you can work on the example uninterrupted.  If you're cool enough to know how to work in one window while occasionally reading stuff in another, so much the better.)

 

Get some text to practice upon.  The text of the Gettysburg Address (Gettysburg.txt) that I have provided will do nicely.  (The "Declaration" text above has artificial p-marks that I put there to show you what they looked like, and hence isn't really suitable to practice with.)

 

Start Word.  Load the file.  Get the problem text up on your screen.

 

Select all of the text from which you wish to strip the p-marks.  (By select, we mean highlight with the mouse cursor or with equivalent keystrokes.  If you've ever done cut-and-paste, you'll know how to do this.)  It may be the entire file, or just a portion in the middle of a bigger document that you're interested in.

 

Macro Mode

 

Go into macro mode.  To do this, select (mouse click or keyboard)

Select Tools.

                  Select Macros.

                                    Select Record New Macro.

By that I mean, select Tools, then Macro from the resulting menu, then Record New Macro from that menu.  [Alt] [T] [M] [R] will also accomplish it.

 

In the box beside Macro Name, type StripParaMark (or any name you like, but be reasonable and consistent), and select OK.

 

Note that a little command window with the word Stop and two symbols appears.  Ignore it for now.

 

Do it Once

 

More Word commands, familiar ones.  With mouse-clicks or keystrokes, go into Replace mode.

Select Edit.

                  Select Replace.

[Alt][E][E] also gets you here.  The familiar window appears.  If you've got the "short" version of the window, you'll have to click on [More].  If instead you see [Less], you've already got the long version.

 

With the cursor in the Find what box, click on [Special].

From the list, select Paragraph Mark.

Now, do it again.  Select [Special] and Paragraph Mark.

You should now see ^p^p in the Find what box.  This is how Word encodes the paragraph mark.  If you can remember that, you can instead just type ^p^p the next time you want a paragraph mark for selection or replacement.  (The "caret" is shifted 6 on most keyboards, and here is used as a special control character.)

 

Tab to the Replace with box.  Here type @@.  I choose double "at" signs as a unique character sequence that I'm not likely to be using for anything else.  There are other possibilities, of course, but don't bet that you won't encounter a double-A or a double-X or a double-exclamation point ever.

Select Replace All.

 

Word will (should!) inform you that it has made three replacements, at least in the Gettysburg text.  Tell it No, you don't want to replace it in the rest of the document.  That's why you selected the text in the first place.

 

Back in Find what, put a single paragraph mark.  You can go Special, Paragraph mark, or just delete one of the two ^p that's already there.  But this time you should have just one of them.

 

Tab to Replace with.  Type just a single space, which should replace the @@ that was there.

Select Replace All.

 

Word will inform you that 21 replacements have been made.  Say No to any more changes.

 

Third time around!  In Find what, enter @@.

 

In Replace with, enter ^p with Special, Paragraph Mark, or other method.  (We'll just restore a single p-mark this time.  In some circumstances, you might want to restore a double p-mark to provide some white space in your text, but you really ought to be doing that with Word's "style" commands.)

Next, Replace All.  No to more changes.

 

Close the Find-and-Replace window.  This concludes the sequence that we want Word to learn for us.  Now we have to ensure that Word remembers the sequence.

 

Saving the Sequence

 

In the tiny command window, Click on the square "Stop" button.  The window disappears.

 

You have created a StripParaMark macro!  It's now part of your Word installation, just as surely as are Bold, Italic and Find-and-Replace.

 

Test It

 

We'll have to test it.  If you don't have another file with p-marks where they oughtn't be, I'd just suggest Close-ing the Gettysburg.doc file without saving any changes, then re-opening it so the old flaws are still there.  However you do it ...

 

Select some text.

Select Tools.

                  Select Macros.

                                    Select Macros this time.

Or, [Alt][T][M][M].   The display shows us that [Alt] [F8] would get us here.

 

Locate StripParaMark on the scrolling list.

Highlight StripParaMark and click Run (or just double-click

 

StripParaMark).

 

Watch it do the work for you.

 

Of course, once you have this working, you may want to improve upon it.  You might want to routinely change the font or the text size or the margins whenever you do this conversion.  The process will be the same: start recording, do all you need to do, and stop recording.  At first, you'll make horrendous mistakes that will utterly ruin your files, so don't practice on anything too important.  But once you get your macro working, you'll take great pride in it, trust me.

 

Bells 'n' Whistles

 

Next time you create a macro via Tools | Macro | Record New Macro, you may want to take advantage of the offer to assign the command to "Keyboard", which is to say, a key sequence.  There are quite a few unused Ctrl and Alt and combination sequences, and you can replace any function-key sequence that you never use.  For example, I never use the function keys to load or save or for editing functions, so I might conveniently redefine key F12 to enact StripParaMark for me.  Just be careful that someone else who uses your system isn't dependent upon that key's default function.  You can even place the command on one of the pull-down menus; Word will guide you in doing this.

 

While it's easiest to assign keystrokes to a macro as you create it, you can do it after the fact via Tools | Customize [Keyboard].  Tools | Customize [Toolbars] will let you add your macros to the existing menus if you're really ambitious.

 

What Lies Beneath

 

One more thing before we leave you . . . .

 

Select Tools | Macro | Macros and locate StripParaMark again and highlight it.  Then click [Edit].

 

What you're now seeing is the VBA code that was generated by your keystroke manipulations.  Read it and you can almost figure out what's going on.  You'll see the search and replace strings, along with a bunch of other options being set up. 

 

I wouldn't recommend changing anything here until you're more familiar with the process, but just wanted to show you what was going on here.  In this editing mode, it's possible to tweak old macros and to create new ones.

Select File | Close and Return to Microsoft Word to get out of the macro editor.

Extra Points

Once you're comfortable with this shortcut, you can improve it by doing the following.  Here' we'll edit the macro code itself!

From MS WORD, select …

Tools

                  Macro

                                    Macros

 

Highlight StripParaMark and select [Edit]

 

Go to the macro listing -- that's the window with Normal – New Macros [Code] in the title bar, and the StripParaMark() code in it.

 

Change (just as you'd edit any document) each of the three occurrences of

        .Wrap = wdFindAsk

to

        .Wrap = wdFindStop

 

Then File | Save Normal

and File | Close and Return to Microsoft Word

 

This change will result in the triple save-and-replace being conducted without your having to confirm each step every time you use it in the future.

 

Go For It!

 

I encourage you to recall those bothersome tasks that you do over and over and consider automating them.  Resolve to never do anything twice, unless you really want to.

Also see More WORD Tricks

 

© 2002 by Don Mankowski

Website