Heading

This is some text inside of a div block.
This is some text inside of a div block.
This is some text inside of a div block.
min read

Define constants for any macro

Word • Macros • Features
Peter Ronhovde
13
min read

We define some common text and a number as VBA constants. Using constants allows them to be seamlessly used in different editing macros saving us the trouble of defining them in each macro where they are needed.

Thanks for your interest

This content is part of a paid plan.

Define constants for any macros

Some quantities are useful across multiple macros, but it is annoying and repetitive to define them in each macro where they're needed. When we define constants, VBA will not allow them to change anywhere, but if the values are fixed, why not define them once and be done with it?

Fortunately, the main difference between a constant that works inside a specific macro and a "global" constant that works with any macro is simply where we declare them. If we create constants at the top of the macro file in the VBA editor, we can use them in any macro within that "module" (see below for more explanation).

We're creating writing and editing macros so our constant values will be representative of the profession, but we can tailor them to our specific workflow or even a working manuscript.

Notation to declare a constant

How do we define typical constants in a macro?

Const SomeConstant As SomeType ' Not done ...

VBA strives to read more like English than most other languages, so why the developers snipped off the last three characters of Constant is questionable, but "Const" it is for the keyword. What do we do with it?

  1. Start with the Const keyword
  2. Give it a unique (something descriptive is even better) constant name which is SomeConstant above
  3. Give it a data type which is the fictional As SomeType here
  4. Define the constant value (see below)

The constant name may only contain alphanumeric characters (as in A – Z, a – z, or 0 – 9) or possibly an underscore _ to simulate a space since spaces are not allowed. VBA does not care about upper or lowercase letters, but the editor will automatically change any later use of the constant to the original case. The name also cannot be exactly the same as one of VBAs keywords like Const, Paragraph, and more; but we could do variations.

Several data types exist in VBA, but the most common valid ones for constants are String, Integer, Long (allows bigger integers), or Boolean (stores True or False values). Fixed values are possible with all these types. Word object data types like a Paragraph or Range are not allowed as constants because we cannot assign a specific, fixed value when they're created, and they regularly change in a document anyhow.

My personal naming convention is to use a capital first letter for constant names, but other conventions exist such as ALL_CAPS_CONSTANT (yuck). VBA doesn't care as long as we follow its naming rules.

Why use constants?

One could argue that something like "Harold" or the number 250 are already constants, so why define either separately as new named constant.

  • Values that are always the same are annoying to recreate each time we need them.
  • We can use the same constant name across multiple macros if it is defined at the top of the macro module.
  • Any changes only need to be made in one place, if needed. Who knows when the value of pi might change? [just kidding] But your main character name for your work in progress might.
  • We're clearly communicating to anyone else using our macros that the values are fixed.

Typing specific numbers into a program (ahem, we call them macros here!) is called "hard coding." While it may happen at times when deadlines loom, it's also problematic when we need to go back and make changes. Which macros did I use them in? Did I change all of them?

Why not avoid the issue ahead of time? We're also providing ourselves a nice name to remind us how it's used.

Defining constant values

We need to take a short detour, but before anyone gets uptight that we're talking about constants not variables, I want to make a point.

Assign a variable value after it is created

In VBA, a variable may be (re)assigned a value anytime after it is declared. Suppose we want to work with an Integer variable (regular counting numbers). We tell VBA what type of data the variable stores and then assign a value to the variable as a separate step.

' Assigning a variable value only works inside a macro or function
Dim SomeVariable As Integer ' Cannot assign a variable value here
SomeVariable = 1 ' This works because it is a variable

Dim is the keyword to tell VBA that we're creating, which we call "declaring," a variable. VBA implicitly creates the variable as a generic Variant data type if the declaration is omitted.

I wish VBA allowed everything to be on one line when assigning an initial value, but alas it does not (unless we use a colon : which is yucky notation). The assignment on the next line works because the variable value can be changed at anytime while a macro is running … thus the name variable.

Constants cannot change after being created

Since the constant value cannot change while a macro runs, we cannot assign the value as a second step like we did with the variable above.

' Cannot change a constant after it is declared because it is fixed
Const SomeConstant As Integer ' Not complete ...
SomeConstant = 2 ' Causes an error with a constant

The constant version causes an error because its value cannot change after it is created.

Uhhhh … so we have a (small) problem.

Assign a constant value when it is created

We must define the value at the same time we declare the constant. Fortunately, it's not difficult, just a tad messy; but at least we get to declare it all on one line. Immediately after the data type, just include a variation of = SomeFixedValue, but the value must be fixed. It cannot refer to a function.

Const MyZero As Integer = 0 ' Pointless but valid constant definition

The zero assignment works because zero is a fixed number.

Constants can refer to prior constants

However, setting the new constant value can refer to a previously defined constant which is helpful at times.

' Pointless but valid constant declaration based on another constant
Const MyOne As Integer = MyZero + 1

This allows us to build more complicated constants and sometimes makes them easier to read. These evaluations are okay to use because VBA can determine the value unambiguously.

Useful macro constants

What kind of author-esque constant ideas exist for VBA writing and editing macros?

Define quote character constants

Modern keyboards inherited some early typewriter limitations by including only straight quotes. Curly quotes existed in print (in the margin) as early as the 16th century which evolved into the standardized characters we know today in modern word processing and printing. Different fonts have variations on the characters, but the application typically converts straight quotes typed by our keyboards into the respective curly quote depending on the document context.

Issues with quote characters

We need to be specific in editing macros since we can't rely on Word to do the quote conversion for us, and we need to detect either form of quotes.

I've used character functions like ChrW(8220) or ChrW(8221) multiple times with a goal of keeping the articles more self-contained, but functions aren't allow when declaring constants. It's gets worse because VBA represents text strings using straight double quotes as in "abc," so how do we represent a double quote as a character within double quotes?

Easy quote constants

Double quotes appear by the thousands in a novel, so how do we define the quote constants and make them easy to use with our writing and editing macros?

After some tinkering around in Word letting smart quotes (in AutoCorrect settings) do their job, we can copy and paste the fixed characters into our VBA editor. The respective quote character constants are:

' Define quote character global constants using fixed characters
Const LeftDQ As String = "“"
Const RightDQ As String = "”"
Const StraightDQ As String = """"
Const LeftSQ As String = "‘"
Const RightSQ As String = "’"
Const StraightSQ As String = "'"

While a human eye might squint hard to distinguish the various constants, it turns out that a computer sees the characters as entirely distinct. The quirky character is the straight double quote which uses a special VBA notation of two double quotes inside a set of double quotes defining the text string.

Just copy and paste these constants at the top of the module (the editor window that probably pops up when you tap Option+F11 in Word for Mac or Alt+F11 in Windows). To work for any macro (be global), they must be at the top of the module before any macros are defined.

Whitespace characters

Many editing macros check for whitespace to either exclude or include it from a document range. A relevant set of characters is:

' Define some common whitespace characters
Const Whitespace As String = " " + vbCr + vbTab

A space is literally " " as plain text. The two constants vbCr and vbTab represent paragraph mark and tab characters, respectively, since we can't type them in a text string in the VBA editor. They're instead defined in a small Word constants table. Without getting into too many details, these are the most common whitespace characters. We "concatenated" them together using plus + signs meaning the three characters are just jammed together one after the other to create a new string containing three characters.

Main character names

I've also defined the name of the main characters of my work in progress as constants. I probably spend months working on a particular novel, so it's not a problem to change the names a few times a year … so they're almost constant constants.

' Define main character names for some dialog or search macros
Const Protagonist1 As String = "Monica"
Const Protagonist2 As String = "Harry"
Const Antagonist1 As String = "Sibil"

Several personal macros use these constant names to quickly edit dialog, but they would also be convenient in a few targeted search macros.

One could argue that "Harry" is already a constant string, so why define it separately as a generic protagonist named constant. The idea is to use it across multiple general macros. I only need to change the name in one, easily accessible place, and the macros work the same with a new name. I don't need to scroll through my list of macros to find the ones that edit dialog while hoping I don't miss a name reference.

Novel word count

I have several macros that track my novel progress. One aspect of that goal is a tentative page count. This is a little trickier than just looking at the page count in the status bar because I prefer to include act, chapter, scene, and subscene headings as well as many novel notes as I write.

Toward that goal, I have a global constant for the estimated number of words per novel page.

' Define an estimated novel words per page count
Const NovelWordsPerPage As Long = 285

Most people default to 250 words per paper page, but my estimations seemed to edge a little higher, thus 285. Estimating each day's contribution to the page count helps me feel better about my progress even if I'm writing in different sections of the novel, and the macro(s) automatically exclude all the non-novel text from the page count.

Adding character constants

Since we're already defining a bunch of constant punctuation characters, we might think ahead about related constants. For example, some dialog editing macros refer to any variation of a double quote character, so we could go ahead and define all three together in a separate constant.

' Define quote character group as a string constant
Const DoubleQuotes As String = LeftDQ + RightDQ + StraightDQ

Such character strings can sometimes be useful with various VBA move methods that require a target character set for the movement. Define whatever groups you find useful.

Fancy shmancy enumerations

If we have more categories or values, a fancier approach called an "enumeration" declares a group of related constants. By the root word of the name, it only assigns numbers, but such enumerations can be used as implicit data types, and we can use the constant values for various validations. All the Word constant tables mentioned throughout the various macro articles on this site are actually enumerations. They are probably not as common for custom writing and editing macros, so they are outside the scope of this article.

What is a module in Word VBA?

If you're familiar with programming in other languages, the code is usually stored in separate text files, but not in VBA. I wish but … if a worm had wings, it would still get eaten by a bird. Something proverbial like that is probably important, but let's talk about VBA.

VBA macros are stored as a hidden part of a document or template (usually the Normal.dotm template) rather than in a separate file. Macro organization gets a tad complicated since we need to use the built-in editor to access our macros in this document metadata.

When a macro is opened for editing, the VBA editor is most like showing a macro module on the right with all the stored macros as plain, editable text. The sidebar contains the document's project and module information with various names and such.

A default module is usually opened when we tap the shortcut Option+F11 in Word for Mac (or Alt+F11 in Windows). Newly recorded macros are usually placed in this default module. Any further organization requires some additional effort on our part.

We're creating constants that are valid across all macros in a module, but they can also be defined across all modules in a project by making them "public."

Project (Public) global constants

If we want our constants to be available to all modules in the project (essentially all separate macro files in a document or template), just prepend the keyword Public to the constant definition.

' Example public constants available to all modules in a project
Public Const LeftDQ As String = "“"
Public Const RightDQ As String = "”"
' And so on ...

Quote characters are essentially universal constants even outside of VBA, so it makes sense to declare them across the entire project.

Can I do this with variables?

Yes and no.

We can define global variables, but VBA does not allow us to assign them a value at the time like we did with the constants above. VBA assigns a default value when they're created, but assigning them any other value must be done in a macro, which is clumsy, clunky, or awkward (pick your favorite adjective).

Global variables have a few isolated uses, but they're frowned upon, in general, since any macro can change them. We "never know" what value they will actually have when we try to use them. Good reasons exist for why people moved away from using them decades ago. Any global variable alternatives are outside the scope of this article.

Affiliate Links

If you're interested in using Word or another tool related to the article, check out these affiliate links. I may make a small commission if you purchase when using them, but there is no increase in cost for you, and it helps to support this site and associated content.

I've been using Microsoft for Business for commercial use (that's us writers) on one of the lower pricing tiers for years. I get to use my macros, have online storage, and don't have to worry about software updates.