Link to home
Create AccountLog in
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
Avatar of John Korchok
John Korchok
Flag of United States of America image

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

Avatar of Keith McElroy
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
Avatar of John Korchok
John Korchok
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account