Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the page number of a table in MS Word Macro?

Tags:

ms-word

vba

I have a document in MS Word 2016 with 200+ pages and even more tables. I need to align all tables on odd pages to the left and I need all tables on even pages aligned to the right. Except for one or two tables which I can amend manually if needed none of the tables span multiple pages. Using

Dim oTable As Table
For Each oTable In ActiveDocument.Tables
    oTable.Rows.Alignment = wdAlignParagraphRight
Next oTable

I can align all tables to the right. When using wdAlignParagraphLeft instead of wdAlignParagraphRight I can align all tables to the left. But I could not figure our how to get the page number of a table so that I can assign the alignment based on the page number a table is on.

(The idea is that if printed as a book, the table are always on the inner side. If there is a better way to accomplish that I'll be listening. If printed as a book and two pages are next to each other the tables should be at the inner side like this:)

+-------------------------------+
|    Even Page  |   Odd page    |
+---------------+---------------+
|       |Table| | |Table|       |
|               |               |
+-------------------------------+
like image 201
yankee Avatar asked Jun 23 '16 19:06

yankee


People also ask

How do I find the Table number in Word?

In the window open, go to “General” section and choose “Table” for caption label. Next check the “Include label and number” box.

How do I automatically insert page numbers in Word table of contents?

Go to References > Table of Contents. Select Custom table of contents. Use the settings to show, hide, and align page numbers, add or change the tab leader, set formats, and specify how many levels of headings to show.

Can I use variables in Word?

Using Variables in Word. A variable serves as a placeholder for information that may change frequently. Using variables in source documents allows you to quickly and easily control the content in your generated output.


1 Answers

Yankee, You can determine the page number that a particular table sits on using:

oTable.Range.Information(wdActiveEndPageNumber)

Therefor, to loop through all of the tables in your document and align them according to the odd or even nature of the page upon which they sit, you would use:

Dim oTable As Table
Dim PageNo As Integer

For Each oTable In ActiveDocument.Tables
    PageNo = oTable.Range.Information(wdActiveEndPageNumber)
    If PageNo Mod 2 = 0 Then    'The page number is EVEN.
        oTable.Rows.Alignment = wdAlignParagraphRight
    Else                        'The page number is ODD.
        oTable.Rows.Alignment = wdAlignParagraphLeft
    End If
Next oTable

Should you have any other questions, don't hesitate to ask.

like image 120
Jim Simson Avatar answered Nov 15 '22 06:11

Jim Simson