Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBA Driving me NUTS!!! 2

Status
Not open for further replies.

corsair2

IS-IT--Management
Feb 21, 2001
55
GB
I have a Word document consisting of multiple (25) tables.
I need to (programmatically) format the width of the second column of each table to "fit to contents" and have tried the following (as well as several other attempts) -

Sub ColumnFormat()
'
TblCount = ActiveDocument.Tables.Count
For x = 1 To TblCount
ActiveDocument.Tables(x).Select
With Selection
.Tables(x).AutoFitBehavior (wdAutoFitContent)
End With
Next x

End Sub

OK, I know this will format the entire table but I've got to start somewhere...

This runs fine for the first table then successfully selects the second table at which point the following error message appears -
"Run-time error '5941':
The requested member of the collection does not exist",

with the line ".Tables(x).AutoFitBehavior (wdAutoFitContent)" highlighted.

Is it even possible to format a single column in vba?

I've tried recording a macro, but the "Table/AutoFit/AutoFitContents" menu item isn't available.
 
Had a quick look at your problem the following code works on all tables for me

Sub tableresize()

Dim tb As Table
For Each tb In ActiveDocument.Tables
tb.AllowAutoFit = True
tb.AutoFitBehavior (wdAutoFitContent)
Next tb


End Sub


hope this helps
::) sdh


Just to do specific columns replace
tb.autofitbehaviour(wdautofitcontent) with
tb.Columns(1).AutoFit
'for column 1 change index for other columns


 

Dim oDoc As Document
Dim oTable As Table
Dim oColumn As Column

Set oDoc = ActiveDocument
For Each oTable In oDoc.Tables
If oTable.Columns.Count >= 2 Then
Set oColumn = oTable.Columns(2)
oColumn.AutoFit
Set oColumn = Nothing
End If

Next oTable
Set oTable = Nothing

Set oDoc = Nothing

'Note however that you'll get an error if a table has horizontally joined cells

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top