Microsoft Corporation
April 1999
Summary: Discusses the details of switching from the Microsoft® WordBasic programming language to Microsoft Visual Basic® for Applications. Covers differences between the two and discusses using the Object Browser, the Selection object, and Range objects. Provides sample macros. (16 printed pages)
Introduction
Logistical Programming Changes in Microsoft Word 97 and Later
Conceptual Differences between WordBasic and Visual Basic for Applications
Determining Which Properties or Methods to Use
Using the Object Browser
Selection Object versus Range Object
Using WordBasic Statements and Functions
Miscellaneous Changes
Example Macros
This article is intended to help users switching from the WordBasic programming language to Visual Basic for Applications, the programming language in Microsoft Word 97 and later.
The first step toward making this switch is to convert your existing WordBasic macros. For information about converting your WordBasic macros, see "Converting WordBasic Macros to Visual Basic" in Microsoft Word Visual Basic Reference Help. This Help topic explains how Word automatically converts macros in Word 6.x or Word 95 templates to Visual Basic for Applications.
Although Word converts your macros, you may need to modify parts of them manually to retain the macros' original functionality. In addition to making modifications to converted WordBasic macros, you may need to write new macros in the future. It's possible to continue using WordBasic statements and functions exposed through the WordBasic object, but gradually you'll want to switch over to Visual Basic for Applications.
To help make the switch to Visual Basic for Applications an easy one, a table of WordBasic commands and their corresponding Visual Basic syntax is included in the Visual Basic Reference Help, in the topic "Visual Basic Equivalents for WordBasic Commands."
Macro Editor—The built-in macro editor available in Word 95 and earlier has been replaced by an integrated Visual Basic development environment, called the Visual Basic Editor. The Visual Basic Editor runs in its own window and looks exactly the same, no matter which Office application you start it from.
Dialog Editor—Versions of Word prior to Word 97 included a separate Dialog Editor application used to design custom dialog boxes. You create custom dialog boxes in Word 97 and later by creating UserForms in the Visual Basic Editor.
Macro Storage—When you create a new macro in the Macros dialog box in Word (point to Macro on the Tools menu, and then click Macros), a new subroutine with the macro name you provide is created in a module. Macros can now be stored in documents as well as templates. You specify the storage location by selecting an item in the Macros in box in the Macros dialog box. The Macros in box includes template names and the name of the active document (for example, "Sales.doc (document)").
The primary difference between Visual Basic for Applications and WordBasic is that WordBasic consists of a flat list of approximately 900 commands, while Visual Basic for Applications consists of a hierarchy of objects, each of which exposes a specific set of methods and properties (similar to statements and functions in WordBasic). Objects are the fundamental building blocks of Visual Basic for Applications; almost everything you do with it involves modifying objects. Every element of Word—documents, paragraphs, fields, bookmarks, and so on—is represented by an object in Visual Basic for Applications. To view a graphical representation of the object model for Word, see the "Object Model Diagrams" appendix in the Microsoft Office 2000/Visual Basic Programmer's Guide (Microsoft Press®, 1999) and "Microsoft Word Objects" in the Microsoft Word Visual Basic Reference Help.
While most WordBasic commands can be run at any time, Visual Basic instructions drill down through the object model to an object that you can manipulate using properties and methods. There are certain objects that you can get to only from other objects: for instance, the Font object, which you can control from the Style, Selection, or the Find object, among others. Before you can change any font-related attributes (such as bold formatting), you need to drill down to the Font object.
The programming task of applying bold formatting demonstrates one of the differences between the two programming languages. The following WordBasic example applies bold formatting to the selection.
Bold 1
Visual Basic for Applications doesn't include a Bold statement and function; instead, there's a Bold property (a property is usually an attribute of an object, such as its size, its color, or whether or not it's bold). The Bold property is a property of the Font object, which is returned by the Font property. The Font property is a property of the Selection object, which is returned by the Selection property. And finally, the Selection property is a property of the Application object, which is returned by the Application property. These relationships are shown in the following object hierarchy.
Using this object hierarchy, you can build the instruction shown in the following example to apply bold formatting to the selection.
Application.Selection.Font.Bold = True
Note Because the Selection property is global, the Application property is optional. To view a list of all the global properties and methods, click <globals> at the top of the Classes list in the Object Browser. For more information about the Object Browser, see Chapter 4, "Understanding Objects and Object Models," in the Microsoft Office 2000/Visual Basic Programmer's Guide.
Instead of being composed of a flat list of commands, Visual Basic consists of a hierarchical arrangement of objects that support a predefined set of properties and methods (as shown in the preceding illustration). The following table shows some common WordBasic instructions and their Visual Basic equivalents.
WordBasic Instruction | Equivalent Visual Basic Instruction |
|
|
|
|
|
|
|
|
|
|
The two instructions in each row of the preceding table are functionally equivalent, but their syntax is dramatically different. Each WordBasic instruction consists of a command name (for example, FileOpen) and any applicable arguments (for example, .Name). Each Visual Basic instruction, on the other hand, is a combination of one or more properties or methods (for example, Documents and Open), followed by any applicable arguments for each (for example, FileName). The properties and methods you use to drill down through the object model are separated by the dot (.) operator.
The Open method in Visual Basic is functionally equivalent to the WordBasic FileOpen statement when the Open method is used with the Documents collection object. The Documents collection is returned by the Documents property. The following illustration shows the path to the Open method.
Following this hierarchy, you can build the instruction shown in the following example to open Mydoc.doc.
Application.Documents.Open FileName:="MYDOC.DOC"
Note The Application property is optional because the Documents property is global.
Visual Basic doesn't include separate statements and functions as in WordBasic. The Bold property is a read/write Boolean property. This means that the Bold property can be set to either True or False (on or off), or the current value can be returned. The following table shows the Visual Basic equivalents for various versions of the WordBasic Bold statement and the WordBasic Bold function.
WordBasic Bold Statement or Function | Equivalent Visual Basic Instruction |
|
|
|
|
|
|
|
|
There are a few techniques for determining which Visual Basic properties or methods you need to use to accomplish a particular programming task. When you're first learning Visual Basic, it's usually best to use the macro recorder. The macro recorder is a tool that translates your actions into Visual Basic instructions. For instance, if you turn on the macro recorder and then open the document named "Examples.doc" in the current folder, the macro recorder records the following instruction.
Documents.Open FileName:="Examples.doc", ConfirmConversions:=False, _
ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
WritePasswordTemplate:="", Format:=wdOpenFormatAuto
To learn more about the preceding instruction, position the insertion point within the word "Open" and then press F1. The Help topic for the Open method explains the arguments you can use with that method. For information about the Documents property, position the insertion point within the word "Documents" and then press F1.
Until you become somewhat familiar with the Word object model, there are a few tools and techniques you can use to help you drill down through the object hierarchy.
Auto List Members—When you type the dot (.) operator after a property or method in the Visual Basic Editor, a list of available properties and methods is displayed. For example, if you type Application., a list containing methods and properties of the Application object appears. Select the method or property you want to use, and then press the TAB key to insert the selected item.
Visual Basic Reference Help—You can use Help to find out which properties and methods you can use with a particular object. Each object topic in Help includes a Properties link and a Methods link, which display, respectively, a list of properties and a list of methods for the object. To jump to the appropriate Help topic, press F1 in the Object Browser or a module.
Object model—For an illustration of how Word objects are arranged in the object hierarchy, see the "Object Model Diagrams" appendix in the Microsoft Office 2000/Visual Basic Programmer's Guide, and "Microsoft Word Objects" in the Microsoft Word Visual Basic Reference Help. Click an object in the graphic to display its corresponding Help topic.
Object Browser—The Object Browser in the Visual Basic Editor displays the members (properties and methods) of the Word objects.
To perform a task in Visual Basic, you need to determine the appropriate object to use. For example, if you want to apply character formatting found in the Font dialog box, use the Font object. Then you need to determine how to drill down through the Word object hierarchy from the Application object to the Font object, through the objects that contain the Font object you want to modify.
To see how this is done:
Given this information, you can write the instruction shown in the following example to apply bold formatting to the selection.
Selection.Font.Bold = True
As you can see, you use methods or properties to drill down to an object. That is, you return an object by applying a method or property to an object above it in the object hierarchy. After you return the object you want, you can apply the methods and control the properties of that object.
Note A given object often exists in more than one place in the object hierarchy. For an illustration of the Word object model, see the "Object Model Diagrams" appendix in the Microsoft Office 2000/Visual Basic Programmer's Guide, and "Microsoft Word Objects" in the Microsoft Word Visual Basic Reference Help. Also, individual properties and methods are often available to multiple objects in the Word object hierarchy. For example, the Bold property is a property of both the Font and Range objects. The following example applies bold formatting to the entire active document (the Content property returns a Range object).
ActiveDocument.Content.Bold = True
Most WordBasic commands modify whatever is selected. For example, the Bold command formats the selection with bold formatting, and the InsertField command inserts a field at the insertion point. Visual Basic supports this same functionality through the Selection object, which you return by using the Selection property. The selection can be a block of text or just the insertion point.
The following Visual Basic example inserts the text "Hello World" and a new paragraph after the selection.
Selection.InsertAfter Text:="Hello World"
Selection.InsertParagraphAfter
In addition to working with the selection, you can define and work with various ranges of text in a document. A Range object refers to a contiguous area in a document, with a starting character position and an ending character position. Similar to the way you use bookmarks in a document, you use Range objects in Visual Basic to identify portions of a document. For example, you can use Visual Basic to apply bold formatting anywhere in a given document without changing the selection. The following example applies bold formatting to the first 10 characters in the active document.
ActiveDocument.Range(Start:=0, End:=10).Bold = True
The following example applies bold formatting to the first paragraph.
ActiveDocument.Paragraphs(1).Range.Bold = True
Both of the preceding examples change the formatting in the active document without changing the selection. In most cases, Range objects are preferred over the Selection object for the following reasons:
For more information about working with Range and Selection objects, see Chapter 5, "Working with Office Applications," in the Microsoft Office 2000/Visual Basic Programmer's Guide.
You can use WordBasic statements and functions in your Visual Basic macros. When you use a WordBasic macro in Word 97 or later, the macro is automatically modified to work with Visual Basic. The following example is a WordBasic macro in a Word 95 template.
Sub MAIN
FormatFont .Name = "Arial", .Points = 10
Insert "Hello World"
End Sub
When the template is opened in Word 97 or later, the macro is converted to the code shown in the following example.
Public Sub Main()
WordBasic.FormatFont Font:="Arial", Points:=10
WordBasic.Insert "Hello World"
End Sub
Each statement in the converted macro begins with the WordBasic property. The WordBasic property returns an object with methods that correspond to the WordBasic statements and functions; this object makes it possible to run WordBasic macros in Word 97 or later. You can reuse old code (instructions that use the WordBasic property) along with new instructions that you write (instructions that don't use the WordBasic property). The following example is functionally equivalent to the preceding macro; however, the second WordBasic instruction has been changed to use the TypeText method of the Selection object.
Public Sub Main()
WordBasic.FormatFont Font:="Arial", Points:=10
Selection.TypeText Text:="Hello World"
End Sub
If you still want to use WordBasic statements in Word 97 or later, precede each WordBasic statement with the WordBasic property followed by the dot (.) operator. The following Visual Basic example moves the insertion point to the beginning of the document.
WordBasic.StartOfDocument
The following example sets justified paragraph alignment and adds 1 inch of space above and below each paragraph in the selection.
WordBasic.FormatParagraph .Alignment = 3, .Before = "1 in", .After = "1 in"
The following example selects all text from the insertion point through the MyMark bookmark. (Notice how the With statement is used to specify the WordBasic object once for a series of instructions.)
With WordBasic
.ExtendSelection
.EditGoTo "MyMark"
.Cancel
End With
Similarly, to use WordBasic functions in Word 97 or later, place the WordBasic property followed by the dot (.) operator before the WordBasic function, and use square brackets around the function name. The following table shows the original WordBasic syntax and the corresponding Visual Basic syntax using the WordBasic property.
WordBasic Instructions | Equivalent Visual Basic Instructions |
|
|
|
|
|
|
Note Methods of the WordBasic object are slower than methods and properties of other Visual Basic objects. For example, WordBasic.FileOpen is slower than Documents.Open. Also, the WordBasic language won't be updated with new commands in the future. Visual Basic includes objects, properties, and methods that duplicate and improve on WordBasic functionality. If you know which WordBasic command to use to perform a particular task, see the conversion table in "Visual Basic Equivalents for WordBasic Commands" in the Microsoft Word Visual Basic Reference Help. This will give you a guide as to which Visual Basic methods and properties to use for specific tasks.
This section outlines other changes to the programming environment in Word 97 or later.
Use the dot (.) operator to separate properties and methods in a Visual Basic instruction. The following example makes the selected text red. The example uses dots to separate the Selection, Font, and ColorIndex properties.
Selection.Font.ColorIndex = wdRed
Use an equal sign (=) to set property values. The following example makes the first paragraph in the active document bold.
ActiveDocument.Paragraphs(1).Range.Bold = True
Use a colon followed by an equal sign (:=) to set an argument of a method, and use a comma to separate arguments of a method. The following example opens MyDoc.doc as a read-only document. FileName and ReadOnly are arguments of the Open method.
Documents.Open FileName:="C:\MyFiles\MyDoc.doc", ReadOnly:=True
Use a space followed by an underscore character ( _) to continue a Visual Basic instruction to the next line. (In WordBasic, the continuation character is a backslash character (\).) The following Visual Basic example spans three lines. The first and second lines end with continuation characters. Press ENTER after typing the continuation character.
Documents.Open FileName:="C:\MyFiles\MyDoc.doc", _
ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=True, _
Revert:=False, Format:=wdOpenFormatAuto
Visual Basic has many more data types than WordBasic does. You can define and use variables without learning about data types, but if you want to write efficient code you should define variables with the appropriate data type (for instance, Integer, String, or Long). The following example defines the counter variable as an integer.
Dim counter As Integer
If you don't specify a data type when you define a variable, Visual Basic automatically specifies the Variant data type, which takes up the largest amount of memory (a minimum of 16 bytes) of all the data types. For information about the various Visual Basic data types, see Chapter 7, "Getting the Most Out of Visual Basic for Applications," in the Microsoft Office 2000/Visual Basic Programmer's Guide, or see "Data Type Summary" in the Visual Basic Reference Help.
Use the ampersand character (&) instead of a plus sign (+) to concatenate strings. To insert special characters, you can continue to use the Chr$() function or you can use one of the following constants: vbCr, vbLf, vbCrLf, or vbTab. The following table shows WordBasic instructions that use concatenated strings and special characters, and their Visual Basic equivalents.
WordBasic Instruction | Equivalent Visual Basic Instruction |
|
|
|
|
|
|
Note Use the ChrW$() function to return a string that contains the character associated with the specified Unicode character.
Visual Basic and WordBasic have similar conditional and looping statements (also known as "control structures"). Visual Basic includes additional looping statements, which are marked with an asterisk in the following table.
Statement | Purpose |
If...Then...Else | Branching when the specified condition is True or False |
Select Case | Selecting a branch from a set of conditions |
Do...Loop* | Looping while or until the specified condition is True |
While...Wend | Looping while the specified condition is True (same as the Do While…Loop form of Do…Loop) |
For...Next | Repeating a group of instructions a specified number of times |
For Each...Next* | Repeating a group of instructions for each object in the specified collection |
Visual Basic includes a For...Next statement for looping through a series of instructions. For looping through objects in a collection, however, the For Each…Next statement works more efficiently. The following WordBasic example creates a new document and then inserts the available font names.
FileNewDefault
For count = 1 To CountFonts()
Insert Font$(count)
InsertPara
Next count
The following Visual Basic example is equivalent to the preceding WordBasic example. Note how the With statement is used to specify the Selection object once for a series of instructions.
Documents.Add
For i = 1 To FontNames.Count
With Selection
.InsertAfter Text:=FontNames(i)
.InsertParagraphAfter
.Collapse Direction:=wdCollapseEnd
End With
Next I
The For Each…Next statement automatically loops through each item in the collection without using the counter variable that the For…Next statement requires. The following Visual Basic example is also equivalent to the preceding WordBasic example. However, it is more efficient than the preceding Visual Basic equivalent, which uses For…Next.
Documents.Add
For Each aFont In FontNames
With Selection
.InsertAfter Text:=aFont
.InsertParagraphAfter
.Collapse Direction:=wdCollapseEnd
End With
Next aFont
Often you can specify measurements in WordBasic macros either in points or as a text measurement (that is, a measurement specified as a string). For example, the following WordBasic example sets justified alignment and adds 1 inch of space above and below each paragraph in the selection (1 inch = 72 points).
FormatParagraph .Alignment = 3, .Before = 72, .After = "1 in"
The following Visual Basic example is equivalent to the preceding WordBasic statement. The With statement is used to specify the Paragraphs collection object once for a series of instructions that set properties of the Paragraphs collection.
With Selection.Paragraphs
.Alignment = wdAlignParagraphJustify
.SpaceBefore = 72
.SpaceAfter = InchesToPoints(1)
End With
You must specify measurements for Word methods and properties in points. You can do this either by specifying the number of points as a number or by using one of the following conversion methods to convert the measurement to points: CentimetersToPoints, InchesToPoints, LinesToPoints, MillimetersToPoints, or PicasToPoints. The preceding example uses the InchesToPoints method to convert 1 inch to points.
This section compares some WordBasic and Visual Basic macros.
The following WordBasic macro applies character and paragraph formatting to the selected text.
Sub MAIN
FormatFont .Font = "Times New Roman", .Points = 14, .AllCaps = 1
FormatParagraph .LeftIndent = "0.5"
SpacePara1
End Sub
The following Visual Basic macro is the equivalent of the WordBasic macro, using the Selection property to apply character and paragraph formatting to the selected text. It uses the Font property to gain access to character-formatting properties, and it uses the ParagraphFormat property to gain access to paragraph-formatting properties and methods.
Sub Macro1()
With Selection.Font
.Name = "Times New Roman"
.Size = 14
.AllCaps = True
End With
With Selection.ParagraphFormat
.LeftIndent = InchesToPoints(0.5)
.Space1
End With
End Sub
The following WordBasic macro deletes the text between the insertion point and the beginning of the sentence that the insertion point is positioned within. The macro then capitalizes the first letter of the remaining text.
Sub MAIN
SentLeft 1, 1
EditCut
ChangeCase 4
End Sub
The following Visual Basic macro uses the MoveStart method to extend the selection to the beginning of the active sentence. The Cut method cuts the selected text and places it on the Clipboard, and the Case property changes the capitalization of the character following the selection.
Sub Macro1()
With Selection
.MoveStart Unit:=wdSentence, Count:=-1
.Cut
.Range.Case = wdTitleSentence
End With
End Sub
Some sources of text include a paragraph mark at the end of every line. This text is difficult to work with in Word because Word treats each line as a separate paragraph and doesn't wrap the text. The following WordBasic macro removes the excess paragraph marks (the end-of-line paragraph marks) but leaves the end-of-paragraph marks.
Sub MAIN
EditReplace .Find = "^p^p", .Replace = "@#$#", \
.Direction = 0, .ReplaceAll, .Format = 0, .Wrap = 1
FileSave
EditReplace .Find = "^p", .Replace = " ", \
.Direction = 0, .ReplaceAll, .Format = 0, .Wrap = 1
FileSave
EditReplace .Find = "@#$#", .Replace = "^p^p", \
.Direction = 0, .ReplaceAll, .Format = 0, .Wrap = 1
End Sub
The preceding macro assumes that two consecutive paragraph marks signify the end of a paragraph. When you remove paragraph marks from text, you usually want to preserve separate paragraphs. For that reason, this macro replaces two consecutive paragraph marks with the placeholder "@#$#". The macro then replaces each remaining paragraph mark with a space. Finally, it replaces the "@#$#" placeholder with two paragraph marks.
The following Visual Basic macro is the equivalent of the preceding WordBasic macro. The macro uses the Execute method of the Find object to execute the three find and replace operations. It uses the Save method to save the active document after each find and replace operation.
Sub Macro1()
With Selection.Find
.Execute FindText:="^p^p", ReplaceWith:="@#$#",
Wrap:=wdFindContinue, _
Replace:=wdReplaceAll, Format:=False, Forward:=True
ActiveDocument.Save
.Execute FindText:="^p", ReplaceWith:=" ", Wrap:=wdFindContinue, _
Replace:=wdReplaceAll, Format:=False, Forward:=True
ActiveDocument.Save
.Execute FindText:="@#$#", ReplaceWith:="^p^p",
Wrap:=wdFindContinue, _
Replace:=wdReplaceAll, Format:=False, Forward:=True
End With
End Sub
The following WordBasic macro uses a While...Wend loop to count the number of times that a specified word appears in a document. The InputBox$() function prompts the user for a search word.
Sub MAIN
count = 0
True = -1
searchtext$ = InputBox$("Please type a word to search for:")
StartOfDocument
EditFind .Find = searchtext$, .Direction = 0, .MatchCase = 0, \
.WholeWord = 0, .Format = 0, .Wrap = 0
While EditFindFound() = True
count = count + 1
RepeatFind
Wend
MsgBox searchtext$ + " was found " + count + " times"
End Sub
The following Visual Basic macro accomplishes the same task as the preceding WordBasic macro by using a Do...Loop statement and the Execute method of the Find object. Because the macro gets to the Find object from a Range object (the Content property returns a Range object), the selection in the document is unchanged. Each time the specified word is found, the count variable changes incrementally by 1. As soon as the Do…Loop statement finishes looping through the document (that is, when it has counted all instances of the specified word), the macro exits the loop and displays the results in a message box.
Sub Macro1()
Dim intCount As Integer
Dim strSearchText As String
intCount = 0
strSearchText = InputBox("Please type a word to search for:")
With ActiveDocument.Content.Find
Do While .Execute(FindText:=strSearchText, Format:=False, _
MatchCase:=False, MatchWholeWord:=False) = True
intCount = intCount + 1
Loop
End With
MsgBox strSearchText & " was found " & intCount & " times"
End Sub
The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, this paper should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication. This document is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS DOCUMENT.
Microsoft, Microsoft Press, and Visual Basic are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.