Working with Multiple Properties or Methods

     

Working with Multiple Properties or Methods

Because most objects have many different properties and methods, you'll often need to perform multiple actions on a single object. This is accomplished easily with multiple statements that set the appropriate properties or run the necessary methods. However, this can be a pain if you have a long object name .

For example, take a look at the FormatParagraph procedure shown in Listing 5.1. This procedure formats a paragraph with six statements. Note that the Paragraph object name ” ThisDocument.Paragraphs(1) ”is quite long and is repeated in all six statements.

Listing 5.1. A Procedure That Formats a Range
 Sub FormatParagraph()     ThisDocument.Paragraphs(1).Style = "Heading 1"     ThisDocument.Paragraphs(1).Alignment = wdAlignParagraphCenter     ThisDocument.Paragraphs(1).Range.Font.Size = 16     ThisDocument.Paragraphs(1).Range.Font.Bold = True     ThisDocument.Paragraphs(1).Range.Font.Color = RGB(255, 0, 0) ' Red     ThisDocument.Paragraphs(1).Range.Font.Name = "Times New Roman" End Sub 

To shorten this procedure, VBA provides the With statement. Here's the syntax:

 With  object  [  statements  ] End With 
graphics/note_icon.gif

You can make the FormatParagraph2 procedure even more efficient when you realize that the Font object also is repeated several times. In this case, you can nest another With statement inside the original one. The new With statement would look like this:

 With .Range.Font      .Size = 16      .Bold = True      .Color = RGB(255, 0, 0)      .Name = "Times New Roman" End With 

object

The name of the object.

statements

The statements you want to execute on object .

The idea is that you strip out the common object and place it on the With line. Then, all the statements between With and End With need only reference a specific method or property of that object. In the FormatParagraph procedure, the common object in all six statements is ThisDocument.Paragraphs(1) . Listing 5.2 shows the FormatParagraph2 procedure, which uses the With statement to strip out this common object and make the previous macro more efficient.

Listing 5.2. A More Efficient Version of FormatParagraph()
 Sub FormatParagraph2()               With ThisDocument.Paragraphs(1)                   .Style = "Heading 1"                   .Alignment = wdAlignParagraphCenter                   .Range.Font.Size = 16                   .Range.Font.Bold = True                   .Range.Font.Color = RGB(255, 0, 0) ' Red                   .Range.Font.Name = "Times New Roman"               End With End Sub 


Absolute Beginner's Guide to VBA
Absolute Beginners Guide to VBA
ISBN: 0789730766
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net