Word vba column width

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Columns.SetWidth method (Word)

vbawd10.chm155910345

vbawd10.chm155910345

word

Word.Columns.SetWidth

42b9c3ce-5743-5143-f8e6-80bcbc0e206d

06/08/2017

medium

Columns.SetWidth method (Word)

Sets the width of columns in a table.

Syntax

expression. SetWidth( _ColumnWidth_ , _RulerStyle_ )

expression Required. A variable that represents a ‘Columns’ collection.

Parameters

Name Required/Optional Data type Description
ColumnWidth Required Single The width of the specified column or columns, in points.
RulerStyle Required WdRulerStyle Controls the way Word adjusts cell widths.

Remarks

The WdRulerStyle behavior described above applies to left-aligned tables. The WdRulerStyle behavior for center- and right-aligned tables can be unexpected; in these cases, the SetWidth method should be used with care.

See also

Columns Collection Object

[!includeSupport and feedback]

1. What I’m Trying To Do

I have a folder with 84 Word documents (.docx). Every document contains a table of identical layout (some of the documents span across 2 pages). However, the column widths are not always the same.

I want to make all the table column widths identical at 2 inches, so I can subsequently save all the files as PDF, and prepare them for use in another process which I will not elaborate on.

2. My Current Approach

I’ve got a Word VBA macro that runs a script (below) over all .docx files in a folder, based on a user-prompted file path. This part works — there’s no problem.

The problem

However, when my script attempts to set all the columns in the document’s tables to the same width, this doesn’t work. It only works, in the example document shown here, on the first 3 columns.

Illustrating the problem with screenshots

original table
Figure 1 (above): This is what the original table looks like in the Word document.

after running macro
Figure 2 (above): This is what the table looks like after running my macro. In this example, I ran the macro to set all column widths to 1.5 (InchesToPoints(1.5)). You can see that only the first 3 columns are adjusted, but columns 4-7 are unmodified.

expected result
Figure 3 (above): This is what I expected the table to look like after running my macro to set all columns to 1.5 inches in width.

Here’s a link to the original document: https://www.dropbox.com/s/cm0fqr6o7xgavpv/1-Accounting-Standards.docx?dl=0

Testing on another file

I tested the macro on another file I created, where I inserted 3 tables.

table test original
Figure 4 (above): I created a new file with 3 tables, all with different column widths.

table test outcome
Figure 5 (above): Running the macro with this test file in the same folder as the example document previously, shows that the macro works, and adjusts the columns in all tables to the specified width.

3. My Question

What’s going on here? Why isn’t SetTableWidths working as expected?

I’m guessing that it’s maybe because the original table in the original word document contains merged cells, otherwise why would the script not work on columns 4-7?

Any help would be greatly appreciated.

4. Word VBA Macro

Sub RunMacroOnAllFilesInFolder()
    Dim flpath As String, fl As String
    flpath = InputBox("Please enter the path to the folder you want to run the macro on.")
    If flpath = "" Then Exit Sub

    If Right(flpath, 1) <> Application.PathSeparator Then flpath = flpath & Application.PathSeparator
    fl = Dir(flpath & "*.docx")
    Application.ScreenUpdating = False
    Do Until fl = ""
        MyMacro flpath, fl
        fl = Dir
    Loop
End Sub

Sub MyMacro(flpath As String, fl As String)
    Dim doc As Document
    Set doc = Documents.Open(flpath & fl)
    'Your code below

    SetTableWidths doc
    DeleteAllHeadersFooters doc

    'your code above
    doc.Save
    doc.Close SaveChanges:=wdSaveChanges
End Sub

Sub SetTableWidths(doc As Document)
    Dim t As Table
    For Each t In doc.Tables
        t.Columns.Width = InchesToPoints(2)
    Next t
End Sub

Sub DeleteAllHeadersFooters(doc As Document)

  Dim sec As Section
  Dim hd_ft As HeaderFooter

  For Each sec In ActiveDocument.Sections
    For Each hd_ft In sec.Headers
      hd_ft.Range.Delete
    Next
    For Each hd_ft In sec.Footers
      hd_ft.Range.Delete
    Next
  Next sec

End Sub

5. Credit & Disclaimers

I didn’t write the VBA macros. I got them online at these two places:

  • https://wordribbon.tips.net/T011693_Setting_Consistent_Column_Widths_in_Multiple_Tables
  • https://www.quora.com/How-do-I-automatically-run-a-macro-on-all-Word-files-docx-in-a-folder
  • http://vba.relief.jp/word-macro-delete-all-headers-and-footers-active-document/

The example documents shown here are property of the Singapore government: http://www.skillsfuture.sg/skills-framework

Word VBA Resize Table Columns and Rows

Jun 27, 2015 in Tables

In this article I will explain how you can use VBA for word to resize table columns and rows.

Every word document has a Tables collection The first step in working with a table in VBA for word is to determine the table index. Tables in a word document start from the index “1” and go up. So for example the first table would be referenced by using the statement below:

Tables.Item(1)

 The second table would be reference by using:

Tables.Item(2)

 and so on . . .

All examples in this article will use the table below as their initial table:

Word, Table Initial


Modify Row Height:

The code below will change the height of the first row of the first table to 50 points:

Tables.Item(1).Rows.Item(1).Height = 50

Result:
Word VBA Resize Column Width Result


Modify Column Width:

The code below will change the width of the first column to 20 points:

Tables.Item(1).Columns(2).Width = 20

Result:
Word VBA Resize Column Result 2
You can download the file and code related to this article from the link below:

  • Resize Columns Rows Tables.docm

See also:

  • VBA, Word Table Insert/Remove Rows/Columns
  • Word VBA, Modify Table Data
  • Word VBA, Delete Empty Rows From Tables

expression.SetWidth(ColumnWidth, RulerStyle)

expression    Required. An expression that returns one of the objects in the Applies To list.

ColumnWidth   Required Single. The width of the specified column or columns, in points.

RulerStyle   Required WdRulerStyle. Controls the way Word adjusts cell widths.

WdRulerStyle can be one of these WdRulerStyle constants.
wdAdjustNone Sets the width of all selected cells or columns to the specified value. Word preserves the width of all non-selected columns, shifting them to the right or left as necessary. This is the default value.
wdAdjustSameWidth Sets the width of the cells in the first column only to the specified value. Word preserves the right edge of the table by adjusting the width of all other cells or columns to the same value.
wdAdjustFirstColumn Sets the width of the cells in the first column only to the specified value. If there is more than one column, Word preserves the right edge of the table and the positions of the other columns.
wdAdjustProportional Sets the width of the cells in the first column only to the specified value. If multiple columns are selected, Word preserves the right edge of the table and the positions of the non-selected columns by proportionally adjusting the width of the other selected columns. If only one cell or column is selected, Word preserves the right edge of the table by proportionally adjusting the width of the other cells or columns.

Remarks

The WdRulerStyle behavior described above applies to left-aligned tables. The WdRulerStyle behavior for center- and right-aligned tables can be unexpected; in these cases, the SetWidth method should be used with care.

Example

This example creates a table in a new document and sets the width of the first cell in the second row to 1.5 inches. The example preserves the widths of the other cells in the table.

Set newDoc = Documents.Add
Set myTable = _
    newDoc.Tables.Add(Range:=Selection.Range, NumRows:=3, _
    NumColumns:=3)
myTable.Cell(2,1).SetWidth _
    ColumnWidth:=InchesToPoints(1.5), _
    RulerStyle:=wdAdjustNone
		

This example sets the width of the cell that contains the insertion point to 36 points. The example also narrows the first column to preserve the position of the right edge of the table.

If Selection.Information(wdWithInTable) = True Then
    Selection.Cells(1).SetWidth ColumnWidth:=36, _
        RulerStyle:=wdAdjustFirstColumn
Else
    MsgBox "The insertion point is not in a table."
End If
		

  • #1

Hi everyone,

I spent hours trying to find a way to edit each column width of a word table from an excel macro and the best I could find is a way to edit every column to the same width, which is not enough. The following code does :
— Open an existing Word file
— Open an existing Excel file
— Copy a range in the Excel file
— Paste the selection into Word file
— Edit the new table created in the Word file

It’s the editing part that’s causing problem. Here’s a video of what I want from this macro in the table editing part : http://s000.tinyupload.com/?file_id=37631956073752272221 (open it wih any web browser)

I have no problem to set all my rows height to 0.5 cm because I want the same height for every row. I used Rows.SetHeight function (as you can see in my code). But when it comes to setting every column individually, I really don’t know what to do. I found some pieces of code that seems to only work in a Word VBA macro like

Code:

ActiveDocument.Table.Columns(1).Width = 30

Thank you very much for your help!

Code:

Sub test()
    folder_Modules_xls = "C:Modules"
    path_template_report = "C:template_report.docx"
    'Get all the selected modules and deduct Bookmarks by removing extension (*.xls or *.xlsx)
    SelectedModules = "test.xlsx"
    
    'OPEN main Word File
    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Open(path_template_report)
    objWord.Visible = True
            
    'Extract Bookmark that will be used in word file.
    Bookmarks = Left(SelectedModules, WorksheetFunction.Search(".", SelectedModules) - 1)
            
    'OPEN Excel file to print into the main Word file
    Set wb = Workbooks.Open(folder_Modules_xls & "" & SelectedModules)
    'READ the number of range name in the xls file corresponding to the number of print area
    printAreaQty = ActiveWorkbook.Names.Count
    'rRange = RecoverNameRange("Print_Area1")


    'In the Word file, go to the corresponding bookmark
    objDoc.Bookmarks(Bookmarks).Select


    'Skip a line
    objWord.Selection.TypeText (vbCrLf) 'return carriage
    
    'Select the print area #1 in the xls file
    Application.Range("Print_Area1").Copy
    'Paste the table at the selected bookmark in the main word doc.
    objWord.Selection.Paste
    Application.CutCopyMode = False
    
    'CUSTOMIZE THE TABLE (the newest)
    With objDoc.Tables(objDoc.Tables.Count)
        .AutoFitBehavior wdAutoFitWindow 'fit to the page
        .Rows.SetHeight RowHeight:=objWord.CentimetersToPoints(0.5), HeightRule:=wdRowHeightExactly 'adjust row height
    End With


    'Close Excel file
    Workbooks(SelectedModules).Close SaveChanges:=False
    Set wb = Nothing
    
    'CLOSING SETTING
    Set objWord = Nothing
    Set objDoc = Nothing
End Sub

Create a Pivot Table on a Map

If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).

  • #2

Can you not use SetWidth for the columns?

Something like this perhaps.

Code:

With objDoc.Tables(objDoc.Tables.Count)
    .AutoFitBehavior wdAutoFitWindow 'fit to the page
    .Rows.SetHeight RowHeight:=objWord.CentimetersToPoints(0.5), HeightRule:=wdRowHeightExactly 'adjust row height
    .Columns.SetWidth ColumnWidth:=objWord.CentimetersToPoints(0.5), RulerStyle:=wdAdjustSameWidth
End With

  • #3

Thank you for your quick response. SetWidth is the first thing I’ve tried. There’s no error but it sets the same width for every column and I want to set different width for each column so I can’t use this function. I also tried :

Code:

.Columns[U][B](1)[/B][/U].SetWidth ColumnWidth:=objWord.CentimetersToPoints(0.5), RulerStyle:=wdAdjustSameWidth

, but it’s not supported.

  • #4

What do you want to set the column widths to?

I ran this code in Word but it should work in Excel.

Code:

Dim tbl As Table

Set tbl = Me.Tables(1) ' Me is the document the code is in

tbl.Columns(1).Width = Application.CentimetersToPoints(3)
tbl.Columns(2).Width = Application.CentimetersToPoints(6)

  • #5

Ok, I added

Code:

Dim tbl As TableSet tbl = objDoc.Tables(1) ' Me is the document the code is in


tbl.Columns(1).Width = Application.CentimetersToPoints(3)
tbl.Columns(2).Width = Application.CentimetersToPoints(6)

And i have «Run-time error ‘5992’ Application-defined or object-defined error». Maybe I don’t get exacly what «Me» is. I used «objDoc» as your «Me». It’s been set as :

Code:

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(path_template_report)

  • #6

Me is the document the code is in, so objDoc is what you should have used in it’s place.

In place of Application you would use objWord, the Word application.

  • #7

Do you think that «Run-time error ‘5992’ Application-defined or object-defined error» is related to the fact that my code relates to :

Code:

Dim tbl As TableSet tbl = objDoc.Tables(1) ' Me is the document the code is in
tbl.Columns(1).Width = Application.CentimetersToPoints(3)
tbl.Columns(2).Width = Application.CentimetersToPoints(6)

This code should produce the error then?

Code:

[CODE]Dim tbl As TableSet tbl = objDoc.Tables(1) ' Me is the document the code is in
tbl.Columns(1).Width = [COLOR=#333333]objWord[/COLOR].CentimetersToPoints(3)
tbl.Columns(2).Width = [COLOR=#333333]objWord[/COLOR].CentimetersToPoints(6)

  • #8

Both sets of code should work as both Word and Excel have CentimetersToPoints.

I only tested on a table I’d created, how exactly did you create/get the table you want to set the column widths for?

  • #9

The step of my sub are :
— Open an existing Word file
— Open an existing Excel file
— Copy a range in the Excel file
— Paste the selection into Word file
— Edit the new table created in the Word file with the same document object I used to paste the excel sheet content.

Can you please download this zip (http://s000.tinyupload.com/?file_id=06192689401906817644) and simply paste its content on C: of your computer. Inside

Report Builder.xlsm, simply hit «Build Report!» button to start the macro. I put in comment the line that’s causing the error so it’s suppose to work. Can you please make this sub work on your side first, that would be very helpful to investigate afterwards. Make sure there’s no other file than «Report_Builder.xlsm» that’s opened when you start the sub.

Thank you!

  • #10

The problem is that you have columns where the cells aren’t all the same width.

gravanoc

NdNoviceHlp

I have a lot of (> 200) tables in Word that have the same layout (two columns, six rows).

I need to adjust the column widths for all of them. Is there a way to automate this?

nixda's user avatar

nixda

26.5k17 gold badges107 silver badges155 bronze badges

asked Nov 11, 2014 at 11:00

countermode's user avatar

You could use a VBA macro to resize every table.

Press ALT+F11 in Word and insert the macro under Project » ThisDocument.
Execute the code with F5

Sub resizeTables()    
  For Each Table In ActiveDocument.Tables
    On Error Resume Next
    Table.Columns(1).Width = 200
    Table.Columns(2).Width = 300
    On Error GoTo 0
  Next    
End Sub
  • Columns(2) represents the column 2 in every table
  • The value Width = 300 is your desired width in pixel. Change it to your needs
  • If your table has less columns than your VBA macro, you will get an exception. For this, I added On Error Resume Next to ignore errors and On Error GoTo 0 to stop this error handling

answered Nov 11, 2014 at 11:29

nixda's user avatar

nixdanixda

26.5k17 gold badges107 silver badges155 bronze badges

Like this post? Please share to your friends:
  • Word vba cell color
  • Word vba application dialogs
  • Word vba all open documents
  • Word vba макрос как запустить
  • Word vba выделить текст в таблице