wordsite.com

   
 


Frequently Asked Questions about Macros

Introduction to VBA Programming

Programming fundamentals

Returning information

Working with tables

Miscellaneous routines

New Routines 1999-2000

Microsoft is a registered trademark of Microsoft Corporation
 
 

   


Introduction to VBA Programming

I can't turn you into a vba expert but I can suggest a way for you to explore vba.

Below, I've listed 22 steps that can be completed in approximately 15 minutes, assuming someone is kind enough to read them to you as you sit at your keyboard. If you have to read them by yourself and turn your attention alternately to the keyboard and back to the steps, then you may need a half hour or longer to complete the steps. Either way, the steps should give you a feel for what it's like to program in vba.

Before starting, launch Word, then press Alt+F11 to launch the vba editor, and then maximize the vba editor window.

Ready? Let's start:

1. In the vba editor, choose Options on the Tools menu and make sure the following checkboxes are checked: Auto List Members Auto Quick Info

2. Press F7 to view a code window, if not already displayed. Then type "Sub Test" and hit the enter key. The vba editor will create a subroutine for you that looks as follows:

Sub Test()
|
End Sub

Notice that the cursor is already flashing inside the subroutine, ready for you to type a command.

3. Now type the following, making special note of the dot at the end of the expression:

ActiveDocument.

4. If you want to work on the active document (and who doesn't) then you have to start this way. (Think Jesus: No one gets to the father except through me!) When you type the "." at the end of the expression a list will pop up. This list is the most amazing guide you can imagine. Each item on the list is either a method or a property of the ActiveDocument or else it's an object unto itself that belongs to the ActiveDocument. For now let's deal with methods. Toward the end of this message we'll deal with properties. At the very end of the message, we'll deal with other objects besides the currently active document.

A method is something you can DO to the activedocument, like print it out. The way to think is this: "I'm trying to do something to the active document as a whole, namely, print it. If I'm patient and scroll through this list, I'll almost certainly find a method that will do this for me." When you first think this way, the word "method" will stick in your throat like a fishbone. Later it will feel more like burnt toast and later still it will feel like candy when you were young. Indeed, in this case, if you're patient, you will scroll far enough to encounter a method called PrintOut. Eureka! You know it's a method (as opposed to a property) because it has an icon next to it that looks like a green brick flying through the air and at this stage the whole concept of method makes you feel like throwing a brick. Nice mnemonic, eh?

Let's give it a try. Since you've scrolled down and selected PrintOut, you can press Tab to accept it or you can double-click it right there in the list. Either way, your statement now looks as follows:

ActiveDocument.PrintOut

5. So far so good. Most people easily get this far. But now what?

6. One possibility is that you're done. After all, you've specified an object (the active document) and you've selected something that you want to do to it (print it out). Indeed, if you're willing to let Word print out the document in whatever way it chooses, then you *are* done.

7. Another possibility is that you want to control how the print job will be carried out. In this case, you must provide some "arguments" (another fishbone, at first). Not to worry. To enter one or more arguments, all you do is type a space after the method and let the editor help you enter them. Arguments are equivalent to the choices you make in the Print dialog box. So go ahead, type a space after PrintOut, so your screen looks like this (the pipe character "|" represents your flashing insertion point after you've typed a space):

ActiveDocument.PrintOut |

8. But wait! When you type the space, the vba editor suddenly gets very helpful again, showing you something like the following:

PrintOut(Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, FileName, ActivePrinterMacGX, ManualDuplexPrint)

9. Aha! Aha! These are the arguments for the PrintOut method. Most of them are immediately recognizable if you've ever paid attention to the Print dialog box. If you're wondering about one or more of them, simply press F1 and you'll call up a help topic that tells you all about each one of them.

10. Now that you can see all the arguments, you can enter values for as many of them as you desire.

One way to do this is to type the name of the argument and then a value, using ":=" to connect them and a comma to separate one argument/value from the next, like so:

ActiveDocument.PrintOut Background:=False, Copies:= 2

Another, boneheaded (in my opinion) way to do this is to enter values for ALL of the arguments, in which case you don't have to type the names of the arguments but you do have to account for ALL of them, as follows:

ActiveDocument.PrintOut False, , , , , , 2, , , , , , ,

11. Let's go with the named-argument approach:

ActiveDocument.PrintOut Background:=False, Copies:= 2

12. That wasn't so painful, was it? Now press F5 to run the subroutine. Or return to Word and choose Tools|Macro|Macros...|Test|Run. (Pressing F5 is easier!)

A quick review before we plunge on to properties. You think: "I'm trying to do something to the active document as a whole, namely, print it. So I start by typing "ActiveDocument." and a list pops up. I scroll through the list and select the PrintOut method. Then I type a space and enter some arguments. In this case, I want background printing off and I want two copies, so I type the names of those arguments and values for each of them. I connect each argument name to its value by using ":=" because I'm part of the cognoscenti."

TAKE A BIG BREATHER HERE BECAUSE NOW IT'S TIME TO EXPLORE PROPERTIES INSTEAD OF METHODS . . .

13. Let's go back to our original assumption, namely, that you want to work on the active document as a whole. In this case, though, let's assume you want to change one of the properties of the document, rather than hit it with a brick.

14. Once again, click in a code window and type the following, making special note of the dot at the end of the expression:

ActiveDocument.

15. Remember, if you want to work on the active document (and who doesn't) then you have to start this way. (No one gets to the father except through me!) When you type the "." at the end of the expression a list will pop up. This list is the most amazing guide you can imagine. Each item on the list is either a method or a property of the ActiveDocument or else it's an object unto itself that belongs to the ActiveDocument. For now let's deal with properties.

A property is a single characteristic. One of the properties of a document is its password. The way to think is this: "I'm trying to change a property of the active document as a whole, namely, its password. If I'm patient and scroll through this list, I'll almost certainly find a password property." Indeed, in this case, if you're patient, you will scroll far enough to encounter a property called Password. Eureka! You know it's a property (as opposed to a method) because it has an icon next to it that looks like a finger pointing at a piece of information. Pretty useless mnemonic, eh?

Let's give it a try. Since you've scrolled down and selected Password, you can press Tab to accept it or you can double-click it right there in the list. Either way, your statement now looks as follows:

ActiveDocument.Password

16. So far so good. Many people easily get this far. But now what?

17. In this case, the next step is to specify a value for the property. To do this, all you do is type a space and an equals sign after the name of the property, so your screen looks like this (the pipe character "|" represents your flashing insertion point after you've typed a space):

ActiveDocument.Password = |

18. Since the vba editor has no idea what value you want to use for a password, it can't offer any suggestions. Instead, you simply have to come up with an idea on your own and type it in, perhaps as follows:

ActiveDocument.Password = "billcoan"

That's it! Now press F5 to run the subroutine. Or return to Word and choose Tools|Macro|Macros...|Test|Run. (Pressing F5 is easier!)

When the statement runs, it will assign "billcoan" to be the password for the currently active document. You might wonder how you were supposed to know that the password had to be enclosed in quotation marks. Well, experience ought to be worth something, oughtn't it? In any case, if you had any question, all you would have had to do is position the cursor anywhere in the name of the property ("Password") and press F1. This would display a help topic that tells you that a password requires a string, which is to say, a bunch of characters inside some quotation marks.

TAKE A BIG BREATHER HERE BECAUSE NOW IT'S TIME TO EXPLORE OBJECTS OTHER THAN THE CURRENTLY ACTIVE DOCUMENT . . .

Let's face it, the currently active document, as a whole, can hold our attention for only so long. After all, you can carry out only so many methods on it (printout, save, saveas, etc., etc.) and you can change only so many of its properties (password, grammar checked, spelling checked, etc., etc.).

But what about working on a particular part of a document, such as the first paragraph all by itself, or on a collection of parts, such as all the paragraphs? Here lies opportunity! After all, documents aren't just objects unto themselves; they're composed of hundreds of other, smaller objects. And you can work on each of those objects individually or as parts of collections.

Let's dig deeper and find out how.

19. The good news is that you can "reach" any part of a document that you want to work on by starting out as though you were going to work on the document itself. In other words, you can start as you almost always start. That is, once again click in a code window and type the following, making special note of the dot at the end of the expression:

ActiveDocument.

20. If you want to work on a part of the active document then you have to start this way. (Remember: No one gets to the father except through me!) When you type the "." at the end of the expression a list will pop up. This list is the most amazing guide you can imagine. Each item on the list is either a method or a property of the ActiveDocument or else it's an object unto itself that belongs to the ActiveDocument. For now let's deal with objects that belong to the ActiveDocument.

An object is something that you can "work on" by applying methods to it or by changing its properties. Word documents contain lots of different types of objects. When multiple objects of the same type exist (or can exist) in the same document, they are treated as "collections." For example, a word document has, or can have, multiple paragraphs. Each paragraph is an object. All of the paragraph objects, together, form the "paragraphs collection."

The easiest document objects (and collections) to think about are paragraphs, words, and characters. The way to think is this: "I'm trying to work on an object that belongs to the active document, namely a paragraph. Since a document can contain more than one paragraph, I'll have to locate the collection of paragraphs and then specify the specific paragraph that I want to work on. If I'm patient and scroll through this list, I'll almost certainly find the collection."

When you first think this way, the words "object" and "collection" will stick in your throat like a fishbone. Later it will feel more like burnt toast and later still it will feel like love when you hit puberty.

Indeed, in this case, if you're patient, you will scroll far enough to encounter a collection called Paragraphs. Eureka! You know it's not a method because it doesn't have an icon next to it that looks like a green brick flying through the air. You don't think of it as a property, either, but you quickly find out that the vba editor *does* think of it as a property. OK, OK. So one of the "properties" of a Word document is that it contains a collection of paragraphs. Great. So "Paragraphs" is a collection of paragraph objects and "Paragraphs" is a property of a Word document. This is confusing, so quit worrying about it. Focus on the list! Find the item you want to work on!

Let's give it a try. Since you've scrolled down and selected Paragraphs, you can press Tab to accept it or you can double-click it right there in the list. Either way, your statement now looks as follows:

ActiveDocument.Paragraphs

21. So far so good. Most people easily get this far. But now what? A major wrinkle, that's what! But hold on, it's easy to deal with. Since "Paragraphs" is a collection, you have to tell the vba editor which paragraph you're interested in. You do this with a number in parentheses. For example, (1) refers to the first paragraph. Let's assume you want to work on the first paragraph in the collection. Type until your statement looks like this:

ActiveDocument.Paragraphs(1).

22. Guess what? You've just "drilled down" from the ActiveDocument object to the Paragraphs collection to the first Paragraph. That is, you've "reached" or "specified" an object that you want to work on. From here on out, life is easy. Why? Because working on a paragraph object is just like working on a document object. As soon as you type the dot after the object, the vba editor shows you a list of all the methods, properties, and objects (or collections of objects) that belong to *your* object. Simply select the method that you want to carry out on your object, or select the property that you want to change, or keep drilling down by selecting an object or collection that belongs to your object. That's all there is to it.

A possible 23rd step would be to repeat Steps 1 -22 but replace all occurrences of "ActiveDocument." with "Selection." This allows you to drill down from the Selection object and discover the various methods, properties, and collections associated with the Selection object.

A possible 24th step would be to repeat Steps 1 -22 but replace all occurrences of "ActiveDocument." with "Application." This allows you to drill down from the Word application object and discover the various methods, properties, and collections associated with that object.