Reading Conditions of a Word table style (for developers)

The problem

A Table style in Word has a .Table.Condition method that returns a ConditionalStyle object. The ConditionalStyle objects refer to different elements of the table: top row, left column, bottom right-hand cell, and so on. There are 12 ConditionalStyle objects in each table style.

If you try to access one of these ConditionalStyle objects, some of the time Word will throw error 5825 'Object has been deleted", even though, plainly, every table style has exactly 12 ConditionalStyle objects, and you can't delete one even if you tried.

What causes this error

You might, for example, assign a table style to a Style variable, and then attempt to access the First Row condition, like this:

Dim sty As Word.Style
Dim cond As Word.ConditionalStyle

    Set sty = ActiveDocument.Styles(wdStyleTableColorfulGrid)
    Set cond = sty.Table.Condition(wdFirstRow)

If you run this code on a new document, Word will throw error 5825 'Object has been deleted'.

The problem seems to be that a table style isn't really ready for use until it's used in some particular ways. Once you have "primed" the style, it will then work fine. That's why the error is so difficult to track down: your code errors out the first time, but runs just fine every other time. Or, the same code will work in some circumstances but not others.

Workaround

The best way I've found to work around this is to read the .Description property before using the .Condition method of a table style's .Table. This somehow 'primes' the Style object and thereafter it will allow you to access the .Condition method.

You don't have to output the .Description in any way. Just reading it and assigning to a variable will do. So this code will run without error:

Dim sty As Word.Style
Dim cond As Word.ConditionalStyle
Dim sPrimeTheStyleObject As String

    Set sty = ActiveDocument.Styles(wdStyleTableColorfulGrid)
    sPrimeTheStyleObject = sty.Description
    Set cond = sty.Table.Condition(wdFirstRow)

The advantage of using the .Description property is that it appears to be innocuous and applies to every style type, so it's easy to get into the habit of reading the .Description before using the .Condition method.

Related pages

Word reports the .BaseStyle of styles inaccurately  (the .BaseStyle property of a style doesn't work until it is "primed", either)