PDA

View Full Version : Macro for applying MS Word styles to tables



kpnishant
07-12-2013, 04:53 AM
Hi,

I'm working on a 250 page MS Word doc that has lots of tables. I need to apply MS Word styles to all tables such that:

1. The first row of each table uses the style "Table Heading"
2. All other rows use "Table Body"

Note: I have these styles pre-created on my MS Word.

Now since this can take a long time to do manually, I want to create a macro for the same. Any help on this is welcome. Thanks in advance.

Addtional Info:
I found/created a working macro to apply table style 'Table Classic 1' to all tables in the doc. Hope this helps.

Sub ApplyTableStyle()
Dim t As Table
For Each t In ActiveDocument.Tables
t.Style = "Table Classic 1"
Next
End Sub

ayltonasc
07-12-2013, 09:20 AM
Hi Kpnishant

try this:


Sub ApplyTableStyle()
Dim t As Table
For Each t In ActiveDocument.Tables
t.Rows.Select
Selection.Style = ActiveDocument.Styles("Table Body")
t.Rows.First.Select
Selection.Style = ActiveDocument.Styles("Table Heading")
Next
End Sub


Regards.
Ailton

kpnishant
07-21-2013, 10:19 PM
Hi Ailton,

Thanks very much for your response. When I run this code, it returns an error:

"Run time error '5991': Cannot access individual rows in this collection because the table has vertically merged cells."

I tried it on more than one document. It returns the same error.

I thought of a different approach to solve the issue.

Would it help if we run a code to select all tables in the doc, and then select style "Table Body" and then run a second code in the same macro to apply "Table Heading" to the first rows?

I did some search to find the following VBA code to select all tables in a doc and it works.

Sub selecttables()
Dim mytable As Table
Application.ScreenUpdating = False

For Each mytable In ActiveDocument.Tables
mytable.Range.Editors.Add wdEditorEveryone
Next
ActiveDocument.SelectAllEditableRanges (wdEditorEveryone)
ActiveDocument.DeleteAllEditableRanges (wdEditorEveryone)
Application.ScreenUpdating = True
End Sub

Hope this helps. And thanks in advance.

fumei
07-22-2013, 12:20 AM
Would it help if we run a code to select all tables in the doc, and then select style "Table Body" and then run a second code in the same macro to apply "Table Heading" to the first rows?

No, that will not work, as VBA does not work with verticcally merged cells. A good reason to avoid merged cells...

There CAN be a workaround. See this thread:
http://www.vbaexpress.com/forum/showthread.php?t=46844

This however deals with columns. not rows - which is what you want it appears. You want to action the first row with the Table Header style. It seems that first row has vertically merged cells. Is there any way you can change them?