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

Validate styles

Word • Macros • Functions
Peter Ronhovde
12
min read

Sometimes we just need to know whether the style exists in the current document. This should be a simple, even trivial, task. Just run a quick command and find out … but it’s more difficult in VBA than it should be.

Thanks for your interest

This content is part of a paid plan.

Problems

Even if you’re a regular user of document templates, you won’t always remember a particular style used in a macro doesn’t exist in the current document. Our methods often morph as we work, so we might create new styles that aren’t copied over to old documents, or we forget to update our original template.

It’s nearly inevitable

The easiest way to avoid any issues is to write macros without any errors and always anticipate every possible problem …

For the rest of us, we better just check.

Does the style exist? Yes or no.

That’s all we need, so we can continue with the real work.

Style errors

Unfortunately, VBA will cause an error if the style doesn’t exist. An otherwise good macros will crash when it encounters a missing style for any reason.

But … wait for it.

Compounding that problem—there is no out-of-the-box way to ask Word VBA if a given style exists in the document.

Arghhh. Yep, you read that right. The issues just keep piling up.

Bad VBA!

In fact, this is a borderline egregious omission on something as fundamental to the application as a style is in Word. Fortunately, there is a solution, but it requires some judicious use of proverbial duct tape.

Is the style valid?

The question is simple. Does the style exist in the current document?

What’s the plan?

Our goal is to return a True or False (Boolean) value based on whether the given style exists or not, so the user can make an informed decision about how to proceed in their main macro.

Given there is no stock method for the task, how can we verify whether a style exists?

Brute force approach

A natural solution might loop through all document styles and check them against our given style name. If we find it, we return a True value. If not, we return False.

Technically, this would work, but it’s slow—way slower than you might imagine for a computer just comparing names, so there’s something strange with how Word references styles under the hood. It’s also unnecessarily labor intensive for such a simple task.

Hack away then

Instead, we just try to access the given style anyhow. Yep, just forge ahead and see what happens. The catch is we need to do something about an inevitable error if we attempt to access an invalid style. It’s an awkward solution, but at least it works, and we can approximate a simple function that should be a standard method in Word VBA.

In full disclosure, I did not invent this approach. I first encountered the idea in a technical forum and then on an abandoned blog while I was scavenging the internet for a solution, but I think the solution below is a little simpler than some others.

How does it work?

More specifically, we pretend to check a property of the given style. If it works, then the style must exist in the document, and we return a True value. If we get an error, we instead return False.

Wait! What?

I hope you cringed at that as much as I did, but let's get started.

Catching errors

The problem is we need a way to recognize the error and not crash the function and by extension the macro that called it. When I say crash, it’s a “fatal” error. If we don’t catch the error, the macro execution stops immediately right in the middle of anything it was doing.

That’s not good.

Fortunately, VBA does have a way to “handle” errors, even if it’s a little cumbersome.

Create function skeleton

We start by creating the function skeleton.

Function IsStyleValid(MyStyle as String) As Boolean
' Include function steps ...

' Return whether style exists
IsStyleValid = False ' Or True?
End Function

What parameters to use?

A Style is its own object type in Word VBA with its own actions (called methods) and data (called properties), so it might be tempting to accept a Style parameter for the function with something like:

Function IsStyleValid(MyStyle as Style) As Boolean ' Not for this function

However, we also want to validate whether a potential style exists, so we can’t assume it’s already a valid style with a defined Style type. It is also common to refer to styles by their text name, so we instead accept a String of plain text characters for the name of a style to validate.

Return type

We’ll return a True or False (Boolean) value based on whether the style exists or not which will allow the function to be used readily in If statements and the like.

Error handlers

This function gets a little technical here, but it’s the only reasonable way to get the job done with VBA as it stands. The explanation below is only a brief introduction to error handling in VBA, and it only covers what we need to know.

Basic error-handling command

The basic error-handling command uses an On Error statement:

On Error DoSomething

Our actual choices of what to do if VBA encounters an error are: disable any error handling, resume running as normal, or go to a different line in the function. The last possibility is what we need here.

Error GoTo statement

We want to go to a special line to run some error-specific steps, so we use:

On Error GoTo StyleError
SomeStyleCommand

GoTo tells the error-handling routine what to do if the function encounters an error when running any commands after it. In this case, we only have a single command attempting to do something with the given style.

If an error occurs, the function is supposed to jump to a section of steps labeled by StyleError, skipping everything in between, and run those steps.

StyleError:
' Some error steps ...

You can pick the line label hopefully using something descriptive. Of course, we also need to provide these error steps.

What do we have so far?

Let’s put together what we have so far.

On Error GoTo StyleError
' Regular function steps are skipped if an error occurs
SomeStyleCommand

StyleError:
' Some error steps ...

In general, we could resume normal macro running after the error-handling steps, but we don’t need that for our style validation macro.

We still need a couple more steps to round out our error-handling code.

Clear any error

We would like to leave the function in good grace by clearing our instigated error thus letting VBA know we took care of the problem.

The standard error object is Err, so we run the Clear command.

Err.Clear

Exit to avoid error steps

Unfortunately as written above, if no error occurs, the function will run the regular function steps … and continue through into the error steps. This happens because the StyleError line is just a line label. It doesn’t do anything by itself.

Oops.

Those extra steps are only meant for an actual error, so we need to quit the function before then.

Exit Function

Resulting error handler

We now have the core of our style validation macro using error handling.

On Error GoTo StyleError
' Regular function steps are skipped if an error occurs
SomeStyleCommand

Exit Function ' Do not run error steps below

StyleError:
' Some error function steps ...
Err.Clear

Check whether a style exists

We need to access the Styles collection in the active document. The reference is as simple as it sounds.

ActiveDocument.Styles

We could reference other Documents that may be open, but it’s simplest to just use the ActiveDocument since that is the most common case by far.

We provide a style name to the collection to attempt to access a specific style.

ActiveDocument.Styles("Some Style")

We literally give the style name as plain text in double quotes. The parentheses are required because we will access a Style property next.

If the style exists, this command will give us access to the Style object corresponding to the style name we provided.

No check whether a style exists?

Here’s the raw deal. This is where we should have a command to just test whether a style exists with something like:

ActiveDocument.Styles.Exists("Some Style") ' No such command

But nothing like this command exists which is why we’re stuck with the error-handling approach.

Attempt to access a style property

We try to use a Style command with the given name. The specific command doesn’t matter for our purposes, so here I’m checking the InUse property.

ActiveDocument.Styles("Some Style").InUse ' Not quite enough ...

The InUse property basically tells us whether a style is modified or in use. It’s a little ambiguous, so it’s not a very “useful” command on its own.

To be clear, the InUse property does not validate whether a style exists in the document by itself. It’s just a means to an end in this function. Do we get an error when attempting to check it?

Store command result

A speedbump here is VBA won’t allow us to just call the function like this. Normally using a command in this form would run the method and just ignore the returned value.

We can do this with our own functions, but for whatever reason VBA won’t let us here. The solution is to store the result in an unused variable.

UnusedResult = ActiveDocument.Styles("Some Style").InUse

This command is a little odd since we don’t use the value, but I suppose we’re already hip deep in hackery today, so we might as well just go for a swim.

Assign valid style result

If the above command succeeds, we know the style exists in the document, so we set the function return value to True.

IsStyleValid = True ' Style exists in document

Assign invalid style result

If we get an error when trying to access this InUse property, we instead return a False value. The catch is we need to return the False result in the error steps.

IsStyleValid = False ' Style does not exist in document

Gotchas

Where could we go wrong in this almost simple, even if a little technical, function?

Exit function

We already mentioned it, but an easy error to make is to omit the Exit Function step after validating a style. Otherwise, the macro will continue through the normal steps into your error steps. For this function, it would change the returned value to False, so a valid style would still return an invalid result!

InUse is not a style validation method!

The InUse property does not validate whether a style exists in the document by itself. It’s just a means to an end.

Rather, InUse indicates whether a built-in style has been modified or is applied somewhere in a document. For a user-defined style, it just indicates the style was created. Its use in the function is just to check if we get an error when trying to access the given style.

If you don’t like the slight confusion, you could just substitute another Style property like BuiltIn, but the result of the function will be the same since we don’t really care about the value of the property for this function.

Final Functions

Putting everything together, the style validation function is:

Function IsStyleValid(MyStyle As String) As Boolean
' Returns a Boolean value whether MyStyle exists in active document
' Uses an error handler to catch when MyStyle does not exist

' Setup error handling for missing style
On Error GoTo StyleError

' Try to access style (do not care about InUse value)
UnusedResult = ActiveDocument.Styles(MyStyle).InUse
' If macro makes it past InUse method, the style exists
IsStyleValid = True ' Return style exists

Exit Function ' Avoid error steps below

StyleError:
' Encountered an error attempting to access given style
IsStyleValid = False ' Return style does not exist
Err.Clear ' Clear error since we are done
End Function

I use a similar set of steps, and I’ve never had a problem, so this approach seems robust enough for regular use. It frustrates me to use such a hacky solution based on an error when we try to access an invalid style, but we’re forced into it.

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.