Object Variables
To access a property of an object, or to invoke a method, you can generally take two approaches: direct or indirect. The indirect approach uses an object variable—that is, a variable that has an object data type, whereas the direct approach does not.
For instance, to set the Bold property of the Font object for the first paragraph in the active document, you can take a direct approach, as in:
ActiveDocument.Paragraphs(1).Range.Font.Bold = True
Alternatively, you can assign an object variable. Here are two possibilities:
Dim rng as Range Set rng = ActiveDocument.Paragraphs(1).Range rng.Font.Bold = True Dim fnt as Font Set fnt = ActiveDocument.Paragraphs(1).Range.Font fnt.Bold = True
Object variables are actually more important than they might seem at first. The most obvious reason for their use is that they can improve code readability when you need to refer to the same object more than once. For instance, instead of writing:
ActiveDocument.Paragraphs(1).Range.Font.Bold = True ActiveDocument.Paragraphs(1).Range.Font.Italic = True ActiveDocument.Paragraphs(1).Range.Font.Underline = False ActiveDocument.Paragraphs(1).Range.Font.Size = 12 ActiveDocument.Paragraphs(1).Range.Font.Name = "Arial"
you can use a Font variable to improve readability as follows:
Dim fnt As Font Set fnt = ActiveDocument.Paragraphs(1).Range.Font fnt.Bold = True fnt.Italic = True fnt.Underline = False fnt.Size = 12 fnt.Name = "Arial"
The With Statement
In fact, VBA provides a With statement to handle ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access