Reputation: 397
I'm trying to autofit table contents in word via vba, however when using autofit, the columns shrink to the right size, but the table size also shrinks in width. How do I keep the table width at its max?
Code:
With tableEmployees
.AllowAutoFit = True
.AutoFitBehavior wdAutoFitWindow
.Columns(1).AutoFit
.Columns(2).AutoFit
.Columns(3).AutoFit
.Columns(4).AutoFit
End With
Table Structure:
id | name | phone | email |
1 | john doe | 555-5555 | john.doe@someadd
ress.com
When I autofit the columns so that the e-mail address appears on one line, the table width shrinks in size. I want the table to take up the empty space on the page so it fills up to the right. The table I have above this one is at full width and I'd like this one to be at full width beneath it but all cell contents visible on one line since there is space for them.
Upvotes: 4
Views: 7391
Reputation: 65
Something like this has worked for me:
With tableEmployees
.AllowAutoFit = True
.AutoFitBehavior wdAutoFitContent
.Columns.AutoFit
.AutoFitBehavior wdAutoFitWindow
.Columns.AutoFit
End With
Autofit to content sizes the columns reasonably with respect to each other.
Window is the width between margins and column borders, so autofit to window will resize the table to the page width inside the margins, and retains the proportions set by autofit to content.
Upvotes: 3
Reputation: 397
Okay I was able to solve my own problem with the following modifications:
With tableEmployees
.PreferredWidthType = wdPreferredWidthPercent
.PreferredWidth = 100
.Columns(1).PreferredWidth = 15
.Columns(2).PreferredWidth = 25
.Columns(3).PreferredWidth = 20
.Columns(4).PreferredWidth = 40
End With
Works nicely!
Upvotes: 1