Ranges provide a powerful VBA tool to help us write more useful as well as less intrusive macros.
Thanks for your interest
This content is part of a paid plan.
Simple Introduction to Ranges
We take our first look under the hood into our new Ranges tool (albeit concisely for now). Stick around because they’ll take our macros up a level.
I’ve briefly mentioned Ranges before since we needed to access them in earlier macros, but we didn't really need to understand them at the time (not that they’re difficult).
What is a Range?
A Range in Word VBA is essentially a span of content in the document. I’ll refer to text almost exclusively since my typical context is creating practical macros for writers.
A Range is much like an invisible Selection with a Start and End as well as other properties like the bold or italics status we can set or change. Ranges also include methods that almost mirror what we can do with the Selection.
There are differences between the Selection and Ranges which we've delved into some in another article, but the similarities will take us a long way toward understanding and implementing Ranges with mostly minor modifications relative to what we might do with the Selection.
What is a property?
Properties describe data or information about the Range like its Start or End position in the document the words contained in the Range (see the Microsoft documentation for Ranges if you're interested, but a later article will cover them in more detail if you prefer).
Sometimes we can only read the property not change it (literally called read-only), but usually we can do both.
What is a method?
Ranges also have methods (essentially actions) they can take. Usually, the actions refer to their own content, but sometimes we can access and act on other portions of the document.
We’ve used several similar methods when working with the Selection object in previous macros. Important examples include collapsing the Range to one end or expanding the Range by various Units (sentences, paragraphs, etc.).
Setting a Range
Ranges are one example of “objects” in VBA consisting of both data (properties) and actions (methods), so we can’t just assign them like we do with numbers or strings for text (like when naming styles).
For example, if we wanted to create a variable and assign it a value of 5, we’d just type:
Since a Range is a VBA object with its own properties and methods, we have to “Set” it rather than just assign it with a plain equals = sign.
Using Set ensures all the date defining the Range are copied into the new Range. With that said, properties of the Range like its Start or End are assigned just as a value using an equals = sign (see below).
There are some idiosyncrasies with using Set and objects in VBA particularly as we manipulate Ranges in our documents, but we'll leave those for the more detailed article.
Invalid Ranges
If a Range becomes invalid or you want to make sure the Range variable cannot be used later in the macro, you can set it to "Nothing."
While this may sound pointless right now, later we'll talk about functions where you don't actually know ahead of time whether the Range will be valid or not, but you'd like to let the user (or yourself when creating a new macro) know when there is a problem.
Resetting a Range
There are several ways to change a valid Range. We could manually set the Start and End values something like
SomeNumber is literally a character position in the document, but the Start must be less than the End position.
We can also use the SetRange command using the Start and End options (called arguments)
In order to do either of these methods, MyRange must already be a valid Range (i.e., not Nothing).
We can also copy (in the literal sense not to the clipboard) and duplicate Ranges, but we'll leave those details for a later article since there is a gotcha to avoid.
What are the differences between the Selection and Ranges?
The shortened explanation is a Range is a general span of document content that is invisible to the user unless the macro makes changes to the document. We can set as many Ranges as we need in a macro; but the Selection is a specific, unique Range for a document with some specialized methods and properties. Our introduction to the Selection talks about this in more detail.
What do we gain by using Ranges?
Why should we use Ranges more than the Selection?
Several good reasons include:
- Make changes to the document without moving the insertion point or changing the Selection (unless we want)
- Fewer chances of causing problems by changing the Selection “live” in a document, so Ranges often allow us to create better, safer macros that don't have unexpected side-effects for the user
- Define more than one Range and use them to compare content. Then take different actions depending on the results (intermediate to advanced).
- Create functions using and manipulating Ranges to extend your macro superpowers (somewhat advanced)
The first is nice for some macros where it is nice to leave the users current position or selection in the document unchanged, so they can keep working without interruption. This feature was my main motivation for introducing Ranges in macros at first.
None of this implies we’ll never use the Selection again. We just mostly reserve it for simpler macros where we’re already moving or changing the user’s selection or insertion point location.
Important Range methods
A Range variable has many methods and properties, but some of the most common are as follows.
Standard clipboard commands
We can copy, cut, or paste Range content using the clipboard
Insert or delete text
We can also insert text into the document using
with a few variations like InsertAfter, InsertParagraph, and several others.
We can also delete the Range contents from the document using
Moving the Range
One common difference is the Selection has a number of specialized move commands like MoveLeft (and the other directions). These are convenient for the Selection since it is such a fundamental object in Word VBA.
Move methods
In Ranges the move methods are condensed into fewer commands, but we lose almost nothing in terms of capability. Specifically, the main move method for a Range is
We can then specify the Unit type based on the common document units such as wdParagaph, wdWord, or others. The direction of up, down, left, or right is inferred by the Unit size and the count. Negative Count values move the MyRange location backward in the document and positive values move forward. For example, this command
moves the MyRange location usually to the previous paragraph (the first of the two steps usually moves to the beginning of the current paragraph unless MyRange is already there).
Most Range moves collapse the Range, so the Start and End positions are the same after the move.
Ranges can’t move up or down by lines within a paragraph is one of two limitations compared to using the Selection. We just have to give our move commands a little differently in some cases, but we gain some nice additional capabilities in return.
There are some additional move method variations like MoveUntil or MoveWhile that allow us to move based on what characters are around the range. These are quite handy as well at times.
GoTo methods
There is also a GoTo method (and slight variations GoToPrevious and GoToNext) where you can specify certain document content types to jump. It gives a different way to handle document navigation in a macro and can be used with bookmarks, headings, etc.
This command moves the Range to the next page in the document.
Adjusting spanned document content
We can directly Expand the Range using
where the Expand command works very similarly to pressing the F8 in Word, but in a macro you can specify a unit directly as is done above. The nice thing about Expand is it will not grow past the Unit given.
There are also specialized move commands like MoveStart, MoveStartWhile, MoveEndUntil, and several others that allow us to manually adjust the Start and End positions of the Range in a macro based on nearby characters. Using these requires a little more explanation, so we'll relegate them to other articles where we need them. Most of these are used and explained in various macros in this blog.
Examples
We've sneakily used Ranges from the start, but to be more concrete with the examples, Ranges allow us to do a multitude of specific actions on our documents. In fairness, many of these examples could be performed using the Selection, but the implementation using Ranges are generally cleaner and don't visibly mess with the user's screen as much.
Navigating the document
We can easily locate specific content in our document. I've created macros to quickly jump to punctuation marks, headings, and more.
You can also take advantage of the Find property to do more powerful searches. I've used this to find empty or incomplete lines which helps me make quick changes elsewhere in my novel and jump right back to where I was writing.
Text manipulation
I've created macros to insert common novel notes as reminders without disturbing my writing location. Tap a quick keyboard shortcut to insert the note, and I just keep writing.
Selecting document content
We can use various move functions to isolate or expand selections in our document.
One macros isolates heading content to select it without having to grab the mouse. We can also quickly select sentences, paragraphs, and more all of which I've used many times.