Dawson Hayfield
Dawson Hayfield

Reputation: 1

Using VBA to Change Text Style in All Tables in a Word Document

I am trying to change the text style inside all tables in a document, and then bold the text in all columns of the first row. I currently have the following...

Sub AutoTableFormat()

Dim tbl As Table
For Each tbl In ActiveDocument.Tables
    txt.Text.Style = ActiveDocument.Styles("Table Text")
Next

End Sub

The following give me an error saying Run-time error '5849': Could not apply the style. I am very new to VBA(just started today) and was hoping for some help. Honestly dont even know where to start with the bolding thing either. Thank you.

Upvotes: 0

Views: 1262

Answers (1)

Timothy Rylatt
Timothy Rylatt

Reputation: 7850

The Visual Basic Editor provides you with three tools to help with coding:

  1. Intellisense - shows you the available properties and methods for objects as you type.
  2. Object Browser - allows you to browse or search the object model
  3. Online help

Although you start out well with a loop through the tables the line inside the loop is completely illogical. What exactly is the variable txt supposed to represent? Where is it declared? What relation does it have to tbl?

Had you used the tools at your disposal you would have discovered that a Table object has a Range which has a Style property. This would have given you:

Sub AutoTableFormat()

    Dim tbl As Table
    For Each tbl In ActiveDocument.Tables
        tbl.Range.Style = ActiveDocument.Styles("Table Text")
    Next

End Sub

Setting the format of the first column is awkward as the Column object does not have a Range. This means you have to loop through each cell of the first column to apply the formatting. A more efficient way of achieving your goal would be to create a table style with all your required formatting and then apply that.

Sub AutoTableFormat()

    Dim tbl As Table
    For Each tbl In ActiveDocument.Tables
        tbl.Style = ActiveDocument.Styles("My Table Style")
        tbl.ApplyStyleFirstColumn
    Next

End Sub

Upvotes: 1

Related Questions