Vba word columns width

I’m going to interpret your question literally: that you merely want to process all the tables in the document and that your code is using Find only in order to locate a table…

The following example shows how you can work with the underlying objects in Word directly, rather than relying on the current Selection, which is what the macro recorder gives you.

So, at the beginning we declare object variables for the Document and a Table. The current document with the focus is assigned to the first. Then, with For Each...Next we can loop through each Table object in that document and perform the same actions on each one.

In this case, the style is specified and the column widths set. Note that in order to give a column width in centimeters it’s necessary to use a built-in conversion function CentimetersToPoints since Word measures column width in Points.

Sub FormatTables
  Dim doc as Document
  Dim tbl as Table

  Set doc = ActiveDocument
  For Each tbl in doc.Tables
    tbl.Style = "eo_tabelle_2"
    tbl.Columns(1).Width = CentimetersToPoints(5.5)
    tbl.Columns(2).Width = CentimetersToPoints(8.5)
    tbl.Columns(3).Width = CentimetersToPoints(7.5)
    tbl.Columns(4).Width = CentimetersToPoints(1.1)
  Next
End Sub

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]

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

  • #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

Which lookup functions find a value equal or greater than the lookup value?

MATCH uses -1 to find larger value (lookup table must be sorted ZA). XLOOKUP uses 1 to find values greater and does not need to be sorted.

  • #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

Студворк — интернет-сервис помощи студентам

Таблица в документе Word создана.
Содержит 17 колонок
Первая должна быть шириной 150 пт
Остальные 24 пт

Как задать ширину колонок в таблице из Excel?

Цепляю весь паровоз сюда до момента , когда нужно начать управление шириной колонок

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Sub Публикация_Word_статобработка()
' лог обработки нужно сохранить в файл word и отформатировать
Dim myWord As Object
 
Set myWord = CreateObject("Word.Application") 'Запускаем новый экземпляр программы Word.Даём этому экземпляру имя "myWord". Через это имя
    'будем обращаться к программе Word.
myWord.Visible = True 'Делаем программу "Word" видимой.
 
Set oDocument = myWord.Documents.Add 'Создаём в программе Word документ и даём этому документу имя "oDocument".
 
With oDocument
    .ActiveWindow.ActivePane.View.Zoom.Percentage = 70 ' показать документ в 70%
    .PageSetup.TopMargin = 28.36 'отступ сверху 1.0 см
    .PageSetup.LeftMargin = 28 'отступ слева 0,99 см
    .Content.Font.Size = 8
    .Content.Font.Name = "Consolas"
End With
With oDocument.Content.ParagraphFormat
    .LeftIndent = 0
    .RightIndent = 0
    .SpaceBefore = 0
    .SpaceBeforeAuto = False
    .SpaceAfter = 0
    .SpaceAfterAuto = False
    .LineSpacingRule = wdLineSpaceSingle
    .CharacterUnitLeftIndent = 0
    .CharacterUnitRightIndent = 0
    .LineUnitBefore = 0
    .LineUnitAfter = 0
End With
 
' вставляем текст заголовка таблицы и дату и время и файл и лист
этап = "2342gadgfsg" ' переменная для заголовка таблицы
myWord.Selection.TypeText Text:="Результаты статистической обработки этапа " & этап
myWord.Selection.TypeParagraph
 
Set tbl = myWord.Selection.Tables.Add(myWord.Selection.Range, 45, 17) ' создаем таблицу 47 строк/5 столбцов
' форматируем таблицу
tbl.Select
myWord.Selection.ParagraphFormat.Alignment = wdAlignParagraphRight ' выравнивание по всей таблице вправо
myWord.Selection.Cells.VerticalAlignment = wdCellAlignVerticalBottom     ' прижимаем содержимое клетки вниз
 
' и вот тут нужно первой колонке присвоить одну ширину, а всем последующим - другую
' как?

Добавлено через 17 минут
Чтобы выделить колонку нашел такой способ

Visual Basic
1
2
tbl.Cell(1, 1).Range.Select
myWord.Selection.SelectColumn

Понравилась статья? Поделить с друзьями:
  • Vba word cell text
  • Vba word application getopenfilename
  • Vba word application filedialog
  • Vba word application commandbars
  • Vba word activedocument words