Avatar of Keith McElroy
Keith McElroy
 asked on

Microsoft Word Table so it is centered based on width of page

Screenshot of 1) table out of alignment 2) table aligned(using the table properties box)  3) Code I need help with to automate calculating what the value should be based on the width of the table

https://www.camscanner.com/share/show?encrypt_id=MHhmNDEzM2Jk&sid=CCBBF59C02C94543yY9fS9XX
Microsoft Word

Avatar of undefined
Last Comment
John Korchok

8/22/2022 - Mon
John Korchok

This will center the table on the page width:
Dim TotalWidth As Long, LeftIndent As Long
For x = 1 To ActiveDocument.Tables(1).Columns.Count
    TotalWidth = TotalWidth + ActiveDocument.Tables(1).Columns(x).Width
Next x
LeftIndent = (ActiveDocument.PageSetup.PageWidth - ActiveDocument.PageSetup.LeftMargin - TotalWidth) / 2
ActiveDocument.Tables(1).Rows.SetLeftIndent LeftIndent:=LeftIndent, RulerStyle:=wdAdjustNone

Open in new window

Keith McElroy

ASKER
Dim TotalWidth As Long, LeftIndent As Long

For each tb In ActiveDocument.Tables
     TotalWidth = 0
     If tb.Title = "BBA Table 127" then

          For x = 1 to tb.Columns.Count

               TotalWidth = TotalWidth + tb.Columns(x).Width 'Error 1


          next x
         Msgbox TotalWidth

        'Error 2. the comma at the end of the following line causes an error,  I remove. the comma and it runs
        'however the PageWidth and LeftMargin return 9999999
         LeftIndent = (ActiveDocument.PageSetup.PageWidth - ActiveDocument.PageSetup.LeftMargin - TotalWidth),
         tb.Rows.SetLeftIndent LeftIndent:=LeftIndent, RulerStyle:=wdAdjustNone
     end if

next

Error 1:
Run-time error '5992':
Cannot access individual columns in this collection because the table has mixed cell widths

Error 2:
Compile Error:  Syntax Error
ASKER CERTIFIED SOLUTION
John Korchok

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes