1. Home
  2. Computing & Technology
  3. Visual Basic
VBA - The Word Working Partner
The AboutVBA.DOC Code Sample

Using the Document object

 More of this Feature
• Part 1: Using VBA with Microsoft Word
• Part 2: Automate Your Letter Writing
• Part 4: Word Objects
• Part 5: The Automated Tutorial Review Program
• Part 6: Using Toolbox Components
 
 Join the Discussion
Create a brilliant VBA app?
Tell Us About It!
 
 Related Resources
• Segment One of the VBA Tutorial
• The About Visual Basic Subjects List
• Beginning Visual Basic
• Visual Basic 6
 
 From Other Guides
• About Desktop Publishing for MS Word
• About Business Software
 
 Elsewhere on the Web
• MS: Word Objects
• MS: Templates vs Add-In's
 

A more "VBA OOP" way to do things like this would be to use events that are triggered by methods of the Application or Document objects rather than just by a magic procedure that is in a particular place with a particular name.

While your Word application has many objects with events that you can use (like the Document object and the Open event will trigger the Document_Open procedure), you can also add your own from the VBA Toolbox.

Initially, let's write a VBA program to automate Word's own capabilities. It's pretty easy to add WordArt to your document without a VBA program. To do this manually, make sure that the WordArt toolbar is visible. Then select the text that you want to be displayed in WordArt, click the Insert WordArt button, select the style of WordArt, the font you want to use and the font size, select bold and italic if you want them, and finally position the WordArt on the page where you want it. Whew!

WordArt Result

Suppose, however, that in your job you frequently need to simply add a line of WordArt to the current paragraph right where the cursor happens to be using the text in the current line as the source. And the size, font, and style are always the same. You can code a quick VBA program to do this at the click of a button:

Sub WordArt()
Dim myRange As Range
Dim myArtText As String
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
myArtText = Selection.Text
Set myRange = _
    ActiveDocument.Range(Start:=Selection.Start, _
    End:=Selection.End)
ActiveDocument.Shapes.AddTextEffect(msoTextEffect22, _
    myArtText, "Impact", 16#, msoFalse, _
    msoFalse, 0, 20, myRange).Select
End Sub

Next page > Word Objects > Page 1, 2, 3, 4, 5, 6

Explore Visual Basic

More from About.com

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

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

All rights reserved.