Vba select table in word

I am looking for a way (or decent introduction) into how to select every table in a Microsoft Word 2013 Document and autofit the contents. Each table is independent of one another and separated by text.

I have established the following code so far:

Sub autofit()

    Selection.Tables(1).AutoFitBehavior (wdAutoFitContent)

End Sub

Which works for individual tables and every column in said table, I understand the format of the «for loop», but would like a nudge to how to transform my individual selection to the entire document.

This is my first post so apologies for any conventions I have missed.

cheezsteak's user avatar

cheezsteak

2,6924 gold badges22 silver badges38 bronze badges

asked Dec 18, 2014 at 17:18

Cellobin22's user avatar

Its pretty trivial to loop them all;

Dim t As Table
For Each t In ActiveDocument.Tables
    t.AutoFitBehavior wdAutoFitContent
Next

answered Dec 18, 2014 at 17:22

Alex K.'s user avatar

Alex K.Alex K.

170k30 gold badges263 silver badges286 bronze badges

1

Add Table to Word Document

This simple macro will add a table to your Word document:

Sub VerySimpleTableAdd()
    Dim oTable As Table
    Set oTable = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=3, NumColumns:=3)
End Sub

Select Table in Word

This macro will select the first table in the active Word document:

Sub SelectTable()
'selects first table in active doc
    If ActiveDocument.Tables.Count > 0 Then    'to avoid errors we check if any table exists in active doc
        ActiveDocument.Tables(1).Select
    End If
End Sub

Loop Through all Cells in a Table

This VBA macro will loop through all cells in a table, writing the cell count to the cell:

Sub TableCycling()
' loop through all cells in table
    Dim nCounter As Long    ' this will be writen in all table cells
    Dim oTable As Table
    Dim oRow As Row
    Dim oCell As Cell

    ActiveDocument.Range.InsertParagraphAfter    'just makes new para athe end of doc, Table will be created here
    Set oTable = ActiveDocument.Tables.Add(Range:=ActiveDocument.Paragraphs.Last.Range, NumRows:=3, NumColumns:=3)    'create table and asign it to variable
    For Each oRow In oTable.Rows    ' outher loop goes through rows
        For Each oCell In oRow.Cells    'inner loop goes
            nCounter = nCounter + 1    'increases the counter
            oCell.Range.Text = nCounter    'writes counter to the cell
        Next oCell
    Next oRow

    'display result from cell from second column in second row
    Dim strTemp As String
    strTemp = oTable.Cell(2, 2).Range.Text
    MsgBox strTemp
End Sub

Create Word Table From Excel File

This VBA example will make a table from an Excel file:

Sub MakeTablefromExcelFile()
'advanced
    Dim oExcelApp, oExcelWorkbook, oExcelWorksheet, oExcelRange
    Dim nNumOfRows As Long
    Dim nNumOfCols As Long
    Dim strFile As String

    Dim oTable As Table    'word table
    Dim oRow As Row    'word row
    Dim oCell As Cell    'word table cell
    Dim x As Long, y As Long    'counter for loops

    strFile = "c:UsersNenadDesktopBookSample.xlsx"    'change to actual path
    Set oExcelApp = CreateObject("Excel.Application")
    oExcelApp.Visible = True
    Set oExcelWorkbook = oExcelApp.Workbooks.Open(strFile)    'open workbook and asign it to variable
    Set oExcelWorksheet = oExcelWorkbook.Worksheets(1)    'asign first worksheet to variable
    Set oExcelRange = oExcelWorksheet.Range("A1:C8")
    nNumOfRows = oExcelRange.Rows.Count
    nNumOfCols = oExcelRange.Columns.Count

    ActiveDocument.Range.InsertParagraphAfter    'just makes new para athe end of doc, Table will be created here
    Set oTable = ActiveDocument.Tables.Add(Range:=ActiveDocument.Paragraphs.Last.Range, NumRows:=nNumOfRows, NumColumns:=nNumOfCols)    'create table and asign it to variable
    '***real deal, table gets filled here
    For x = 1 To nNumOfRows
        For y = 1 To nNumOfCols
            oTable.Cell(x, y).Range.Text = oExcelRange.Cells(x, y).Value
        Next y
    Next x
    '***
    oExcelWorkbook.Close False
    oExcelApp.Quit
    With oTable.Rows(1).Range    'we can now apply some beautiness to our table :)
        .Shading.Texture = wdTextureNone
        .Shading.ForegroundPatternColor = wdColorAutomatic
        .Shading.BackgroundPatternColor = wdColorYellow
    End With
End Sub
  • Hi,

    In Word, there is no such settings or button to directly select all tables at once.

    Maybe some codes can be used for your requirement. I found the following article provide a code about select all tables in a document:

    https://www.extendoffice.com/documents/word/639-word-select-all-tables.html

    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please
    make sure that you completely understand the risk before retrieving any suggestions from the above link.

    It indicates that we can use a VBA code to select all tables in the document :

    Step 1: Press “Alt-F11” to open the Microsoft Visual Basic for Application window;
    Step 2: Click Module on the Insert tab, copy and paste the following VBA code into the Module window;

    Sub selecttables()
     Dim mytable As Table
     Application.ScreenUpdating = False

     For Each mytable In ActiveDocument.Tables
     mytable.Range.Editors.Add wdEditorEveryone
     Next
     ActiveDocument.SelectAllEditableRanges (wdEditorEveryone)
     ActiveDocument.DeleteAllEditableRanges (wdEditorEveryone)
     Application.ScreenUpdating = True
     End Sub

    Step 3: Save the VBA file and then close the Module window;
    Step 4: Click Run Macro on the Run tab;
    Step 5: Select the saved VBA file and click Run button.

    If you still have any further issue about it, it is better to ask a question in

    Word for Developers forum for more help.


    Regards,

    Winnie Liang


    Please remember to
    mark the replies as an answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact
    tnmff@microsoft.com.

    • Proposed as answer by

      Monday, October 10, 2016 2:50 AM

    • Marked as answer by
      Winnie LiangMicrosoft contingent staff
      Tuesday, October 11, 2016 10:02 AM

  • Old

    04-12-2012, 09:22 PM

    ubns
    ubns is offline

    Macro to select tables Windows 7 32bit Macro to select tables Office 2010 32bit

    Competent Performer

    Macro to select tables

     

    Join Date: Apr 2012

    Posts: 177

    ubns is on a distinguished road

    Default

    Macro to select tables


    Hi,

    I was trying to get macro for selecting certain tables and then copy them to a new document. I have got the code to select certain tables -but do not know how to copy these tables to new document

    Here is the code:

    Code:

    Sub SelectRange()
    Dim rngParagraphs As Range
    Set rngParagraphs = ActiveDocument.Range( _
    Start:=ActiveDocument.Tables(1).Range.Start, _
    End:=ActiveDocument.Tables(8).Range.End)
    rngParagraphs.Select
    End Sub

    Reply With Quote

    Old

    04-14-2012, 12:36 PM

    Stefan Blom's Avatar

    Stefan Blom
    Stefan Blom is offline

    Macro to select tables Windows 7 64bit Macro to select tables Office 2010 32bit

    Moderator

     

    Join Date: Aug 2011

    Posts: 3,750

    Stefan Blom is a name known to allStefan Blom is a name known to allStefan Blom is a name known to allStefan Blom is a name known to allStefan Blom is a name known to allStefan Blom is a name known to all

    Default


    Actually, you don’t have to select anything. Once you have defined the range, make use of the Copy method, create a new document, and paste:

    Code:

    Dim rngParagraphs As Range
    Dim NewDoc As Document
     
    Set rngParagraphs = ActiveDocument.Range( _
    Start:=ActiveDocument.Tables(1).Range.Start, _
    End:=ActiveDocument.Tables(8).Range.End)
    rngParagraphs.Copy
    Set NewDoc = Documents.Add
    NewDoc.Content.Paste

    __________________
    Stefan Blom
    Microsoft Word MVP

    Reply With Quote

    Old

    04-15-2012, 04:08 PM

    ubns
    ubns is offline

    Macro to select tables Windows 7 32bit Macro to select tables Office 2010 32bit

    Competent Performer

    Macro to select tables

     

    Join Date: Apr 2012

    Posts: 177

    ubns is on a distinguished road

    Default


    Thanks Stefan.

    Can you suggest the macro which should do the same task as above however rather than we selecting the tables by (using the code (Tables (1) — Table (8)), the macro should select all the tables till the start of another heading of the document. Once selection is done then macro should copy and paste it to another document.

    Thanks.

    Reply With Quote

    Old

    04-15-2012, 06:29 PM

    Default


    Hi ubns,

    This is the first time youve mentioned headings in this thread.

    For some code to process content between headings, see: https://www.msofficeforums.com/vba/1…ific-text.html

    You need to note that vba can’t select multiple discontiguous ranges. So, if the there is anything between the tables, they have to be either: copied & pasted individually; or copied as a group along with the intervening content, which can then be deleted after pasting.

    __________________
    Cheers,
    Paul Edstein
    [Fmr MS MVP — Word]

    Reply With Quote

    Old

    04-15-2012, 10:29 PM

    ubns
    ubns is offline

    Macro to select tables Windows 7 32bit Macro to select tables Office 2010 32bit

    Competent Performer

    Macro to select tables

     

    Join Date: Apr 2012

    Posts: 177

    ubns is on a distinguished road

    Default


    Thanks I have looked into that, however I dont know how can that code be helpful here?

    Reply With Quote

    Old

    04-15-2012, 11:44 PM

    Default


    Hi ubns,

    The code shows how one can continue extending a range until a certain heading (based on a heading Style) is reached. How/whether it might be helpful for you depends on what you’re trying to achieve. However, since you haven’t said anything about: what kinds of headings you’re working with; how the starting point might be defined; or what content there might be between the tables you’re interested in, no specific advice can be given.

    __________________
    Cheers,
    Paul Edstein
    [Fmr MS MVP — Word]

    Reply With Quote

    Содержание

    • 1 Adding a Column to a Table
    • 2 Adding a Row to a Table
    • 3 Converting a Table or Rows to Text
    • 4 Converts the current selection to a five-column table, separating the information at commas.
    • 5 Declare the variable tempTable and then select the first table in the document named Log.doc and assign its Range object to tempTable
    • 6 Deletes the first cell in the first row of the first table in the active document and shifts the other cells in the first row to the left to fill the gap:
    • 7 delete the column in which the range testRange ends if the range is more than one column wide:
    • 8 Deleting a Column from a Table
    • 9 Deleting a Row from a Table
    • 10 Deleting Cells
    • 11 Entering Text in a Cell
    • 12 Finding Out Where the Selection Is in the Table
    • 13 Inserting a Cell
    • 14 inserts a new, blank, non-autofitting table containing 10 rows and 5 columns at the current position of the insertion point in the active document:
    • 15 Making Sure the Selection Is within a Table
    • 16 Returning the Text within a Cell
    • 17 Selecting a Column
    • 18 Selecting a Range of Cells
    • 19 Selecting a Row
    • 20 Selecting a Table in the active document:
    • 21 Selects the first table in the current selection:
    • 22 Set the Height property of the row or rows in question by specifying the height in points
    • 23 Setting the Height of One or More Rows
    • 24 Setting the Width of a Column
    • 25 Strip off the last two characters when assigning the Text property to a string:
    • 26 The SetWidth method sets the width of one or more columns and specify how the other columns in the table should change as a result: expression.SetWidth ColumnWidth, RulerStyle
    • 27 The Width property lets you change the width of a column without worrying about the effect on the other columns. Specify the width you want in points-for example:
    • 28 Use the ConvertToText method with a Table object, a Row object, or a Rows collection: converts only the first row of the selected table to tab-delimited text
    • 29 wdDeleteCellsEntireRow deletes the whole row.
    • 30 wdDeleteCellsShiftLeft moves cells across to the left to fill the gap.
    • 31 wdDeleteCellsShiftUp moves cells up to fill the gap.
    • 32 wdEndOfRangeColumnNumber returns the number of the column in which the end of the selection or range falls.

    Adding a Column to a Table

       <source lang="vb">
    
    

    «The following statements use the Count property to check the number of columns in the first table in the active document and
    Sub add()

       With ActiveDocument.Tables(1)
           .Select
           If .Columns.Count < 5 Then
               Do Until .Columns.Count = 5
                   .Columns.add BeforeColumn:=.Columns(.Columns.Count)
               Loop
           End If
       End With
    

    End Sub

    </source>
       
      
    

    Adding a Row to a Table

       <source lang="vb">
    
    

    Sub addRow()

       Documents("yourDoc.doc").Tables(1).Rows.Add BeforeRow:=1
    

    End Sub

    </source>
       
      
    

    Converting a Table or Rows to Text

       <source lang="vb">
    
    

    Sub sep()

       Selection.Tables(1).ConvertToText Separator:="*"
    

    End Sub

    </source>
       
      
    

    Converts the current selection to a five-column table, separating the information at commas.

       <source lang="vb">
    
    

    Sub sele()

       Set myTable = Selection.ConvertToTable(wdSeparateByCommas, _
           Selection.Paragraphs.Count, 5, , , , , , , , , , , True, _
           wdAutoFitContent, wdWord9TableBehavior)
    

    End Sub

    </source>
       
      
    

    Declare the variable tempTable and then select the first table in the document named Log.doc and assign its Range object to tempTable

       <source lang="vb">
    
    

    Sub tableSel()

       Dim tempTable
       Documents("Log.doc").Tables(1).Select
       Set tempTable = Selection.Tables(1).Range
       tempRange.Tables(2).Select
    

    End Sub

    </source>
       
      
    

    Deletes the first cell in the first row of the first table in the active document and shifts the other cells in the first row to the left to fill the gap:

       <source lang="vb">
    
    

    Sub del()

       ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
           ShiftCells:=wdDeleteCellsShiftLeft
    

    End Sub

    </source>
       
      
    

    delete the column in which the range testRange ends if the range is more than one column wide:

       <source lang="vb">
    
    
        With testRange
            If .Information(wdStartOfRangeColumnNumber) <> _
                .Information(wdEndOfRangeColumnNumber) Then _
                .Tables(1).Columns(.Information _
                (wdEndOfRangeColumnNumber)).Delete
        End With
    </source>
       
      
    

    Deleting a Column from a Table

       <source lang="vb">
    
    

    Sub del()

       ActiveDocument.Tables(1).Columns(1).Delete
    

    End Sub

    </source>
       
      
    

    Deleting a Row from a Table

       <source lang="vb">
    
    

    Sub del()

       Documents("yourDoc.doc").Tables(3).Rows(1).Delete
    

    End Sub

    </source>
       
      
    

    Deleting Cells

       <source lang="vb">
    
    

    «wdDeleteCellsEntireColumn deletes the whole column the specified cell or cells is in.
    Sub del()

       ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
           ShiftCells:=wdDeleteCellsEntireColumn
    

    End Sub

    </source>
       
      
    

    Entering Text in a Cell

       <source lang="vb">
    
    

    Sub text()

       With Selection.Tables(1).Rows(1)
           .Cells(1).Range.text = "Sample text in first cell."
           .Cells(2).Range.text = "Sample text in second cell."
           .Cells(3).Range.text = "Sample text in third cell."
       End With
    

    End Sub

    </source>
       
      
    

    Finding Out Where the Selection Is in the Table

       <source lang="vb">
    
    

    Sub sel()

       If Selection.Information(wdAtEndOfRowMarker) = True Then _
           Selection.MoveLeft Unit:=wdCharacter, Count:=1
    

    End Sub

    </source>
       
      
    

    Inserting a Cell

       <source lang="vb">
    
    

    Sub insert()

       Documents("Tables.doc").Tables(1).Rows(1).Cells.Add _
           BeforeCell:=Documents("Tables.doc").Tables(1).Rows(1).Cells(2)
    

    End Sub

    </source>
       
      
    

    inserts a new, blank, non-autofitting table containing 10 rows and 5 columns at the current position of the insertion point in the active document:

       <source lang="vb">
    
    

    Sub table()

       ActiveDocument.Tables.add Range:=Selection.Range, NumRows:=10, _
           NumColumns:=5, DefaultTableBehavior:=wdWord8TableBehavior
    

    End Sub

    </source>
       
      
    

    Making Sure the Selection Is within a Table

       <source lang="vb">
    
    

    Sub withTable()

       If Selection.Information(wdWithInTable) = True Then
           "take actions here
       End If
    

    End Sub

    </source>
       
      
    

    Returning the Text within a Cell

       <source lang="vb">
    
    

    Sub text()

       Dim strCellText As String
       strCellText = ActiveDocument.Tables(1).Rows(2).Cells(1).Range.Text
       Debug.Print strCellText
    

    End Sub

    </source>
       
      
    

    Selecting a Column

       <source lang="vb">
    
    

    «To select a column, use the Select method with the appropriate Column object.
    Sub sel()

       Documents("yourDoc.doc").Tables(3).Columns(2).Select
    

    End Sub

    </source>
       
      
    

    Selecting a Range of Cells

       <source lang="vb">
    
    

    «To select a range of cells within a table, declare a Range variable, assign to it the cells you want to select, and then select the range
    Sub cellSel()

       Dim myCells As Range
       With ActiveDocument
           Set myCells = .Range(Start:=.Tables(1).Cell(1, 1).Range.Start, _
               End:=.Tables(1).Cell(1, 4).Range.End)
           myCells.Select
       End With
    

    End Sub

    </source>
       
      
    

    Selecting a Row

       <source lang="vb">
    
    

    Sub sel()

       Documents("Tables.doc").Tables(.Tables.Count).Rows.Last.Select
    

    End Sub

    </source>
       
      
    

    Selecting a Table in the active document:

       <source lang="vb">
    
    

    Sub table1()

       ActiveDocument.Tables(1).Select
    

    End Sub

    </source>
       
      
    

    Selects the first table in the current selection:

       <source lang="vb">
    
    

    Sub tableSel1()

       Selection.Tables(1).Select
    

    End Sub

    </source>
       
      
    

    Set the Height property of the row or rows in question by specifying the height in points

       <source lang="vb">
    
    

    Sub height()

       Documents("Tables.doc").Tables(3).Rows(3).Height = 33
    

    End Sub

    </source>
       
      
    

    Setting the Height of One or More Rows

       <source lang="vb">
    
    

    Sub rowHeight()

       ActiveDocument.Tables(4).Rows(2).HeightRule = wdRowHeightAuto
    

    End Sub

    </source>
       
      
    

    Setting the Width of a Column

       <source lang="vb">
    
    

    Sub auto()

       ActiveDocument.Tables(1).Columns.AutoFit
    

    End Sub

    </source>
       
      
    

    Strip off the last two characters when assigning the Text property to a string:

       <source lang="vb">
    
    

    Sub strip()

       Dim strCellText As String
       
       strCellText = ActiveDocument.Tables(3).Rows(2).Cells(1).Range.Text
       Debug.Print strCellText
       strCellText = Left(strCellText, Len(strCellText) - 2)
       Debug.Print strCellText
    

    End Sub

    </source>
       
      
    

    The SetWidth method sets the width of one or more columns and specify how the other columns in the table should change as a result: expression.SetWidth ColumnWidth, RulerStyle

       <source lang="vb">
    
    

    Sub ruler()

       ActiveDocument.Tables(1).Columns(2).SetWidth ColumnWidth:=50, _
           RulerStyle:=wdAdjustProportional
    

    End Sub

    </source>
       
      
    

    The Width property lets you change the width of a column without worrying about the effect on the other columns. Specify the width you want in points-for example:

       <source lang="vb">
    
    

    Sub width()

       ActiveDocument.Tables(11).Columns(44).Width = 100
    

    End Sub

    </source>
       
      
    

    Use the ConvertToText method with a Table object, a Row object, or a Rows collection: converts only the first row of the selected table to tab-delimited text

       <source lang="vb">
    
    

    Sub tab()

       Selection.Tables(1).Rows(1).ConvertToText Separator:=wdSeparateByTabs
    

    End Sub

    </source>
       
      
    

    wdDeleteCellsEntireRow deletes the whole row.

       <source lang="vb">
    
    

    Sub del()

       ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
           ShiftCells:=wdDeleteCellsEntireRow
    

    End Sub

    </source>
       
      
    

    wdDeleteCellsShiftLeft moves cells across to the left to fill the gap.

       <source lang="vb">
    
    

    Sub del()

       ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
           ShiftCells:=wdDeleteCellsShiftLeft
    

    End Sub

    </source>
       
      
    

    wdDeleteCellsShiftUp moves cells up to fill the gap.

       <source lang="vb">
    
    

    Sub del()

       ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
           ShiftCells:=wdDeleteCellsShiftUp
    

    End Sub

    </source>
       
      
    

    wdEndOfRangeColumnNumber returns the number of the column in which the end of the selection or range falls.

       <source lang="vb">
    
    
        With testRange
            If .Information(wdStartOfRangeColumnNumber) <> _
                .Information(wdEndOfRangeColumnNumber) Then _
                .Tables(1).Columns(.Information _
                (wdEndOfRangeColumnNumber)).Delete
        End With
    </source>
    

    Создание таблиц в документе Word из кода VBA Excel. Метод Tables.Add, его синтаксис и параметры. Объекты Table, Column, Row, Cell. Границы таблиц и стили.

    Работа с Word из кода VBA Excel
    Часть 4. Создание таблиц в документе Word
    [Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]

    Таблицы в VBA Word принадлежат коллекции Tables, которая предусмотрена для объектов Document, Selection и Range. Новая таблица создается с помощью метода Tables.Add.

    Синтаксис метода Tables.Add

    Expression.Add (Range, Rows, Columns, DefaultTableBehavior, AutoFitBehavior)

    Expression – выражение, возвращающее коллекцию Tables.

    Параметры метода Tables.Add

    • Range – диапазон, в котором будет создана таблица (обязательный параметр).
    • Rows – количество строк в создаваемой таблице (обязательный параметр).
    • Columns – количество столбцов в создаваемой таблице (обязательный параметр).
    • DefaultTableBehavior – включает и отключает автоподбор ширины ячеек в соответствии с их содержимым (необязательный параметр).
    • AutoFitBehavior – определяет правила автоподбора размера таблицы в документе Word (необязательный параметр).

    Создание таблицы в документе

    Создание таблицы из 3 строк и 4 столбцов в документе myDocument без содержимого и присвоение ссылки на нее переменной myTable:

    With myDocument

    Set myTable = .Tables.Add(.Range(Start:=0, End:=0), 3, 4)

    End With

    Создание таблицы из 5 строк и 4 столбцов в документе Word с содержимым:

    With myDocument

    myInt = .Range.Characters.Count 1

    Set myTable = .Tables.Add(.Range(Start:=myInt, End:=myInt), 5, 4)

    End With

    Для указания точки вставки таблицы присваиваем числовой переменной количество символов в документе минус один. Вычитаем единицу, чтобы исключить из подсчета последний знак завершения абзаца (¶), так как точка вставки не может располагаться за ним.

    Последний знак завершения абзаца всегда присутствует в документе Word, в том числе и в новом без содержимого, поэтому такой код подойдет и для пустого документа.

    При создании, каждой новой таблице в документе присваивается индекс, по которому к ней можно обращаться:

    myDocument.Tables(индекс)

    Нумерация индексов начинается с единицы.

    Отображение границ таблицы

    Новая таблица в документе Word из кода VBA Excel создается без границ. Отобразить их можно несколькими способами:

    Вариант 1
    Присвоение таблице стиля, отображающего все границы:

    myTable.Style = «Сетка таблицы»

    Вариант 2
    Отображение внешних и внутренних границ в таблице:

    With myTable

    .Borders.OutsideLineStyle = wdLineStyleSingle

    .Borders.InsideLineStyle = wdLineStyleSingle

    End With

    Вариант 3
    Отображение всех границ в таблице по отдельности:

    With myTable

    .Borders(wdBorderHorizontal) = True

    .Borders(wdBorderVertical) = True

    .Borders(wdBorderTop) = True

    .Borders(wdBorderLeft) = True

    .Borders(wdBorderRight) = True

    .Borders(wdBorderBottom) = True

    End With

    Присвоение таблицам стилей

    Вариант 1

    myTable.Style = «Таблица простая 5»

    Чтобы узнать название нужного стиля, в списке стилей конструктора таблиц наведите на него указатель мыши. Название отобразится в подсказке. Кроме того, можно записать макрос с присвоением таблице стиля и взять название из него.

    Вариант 2

    myTable.AutoFormat wdTableFormatClassic1

    Выбирайте нужную константу с помощью листа подсказок свойств и методов – Auto List Members.

    Обращение к ячейкам таблицы

    Обращение к ячейкам второй таблицы myTable2 в документе myDocument по индексам строк и столбцов:

    myTable2.Cell(nRow, nColumn)

    myDocument.Tables(2).Cell(nRow, nColumn)

    • nRow – номер строки;
    • nColumn – номер столбца.

    Обращение к ячейкам таблицы myTable в документе Word с помощью свойства Cell объектов Row и Column и запись в них текста:

    myTable.Rows(2).Cells(2).Range = _

    «Содержимое ячейки во 2 строке 2 столбца»

    myTable.Columns(3).Cells(1).Range = _

    «Содержимое ячейки в 1 строке 3 столбца»

    В таблице myTable должно быть как минимум 2 строки и 3 столбца.

    Примеры создания таблиц Word

    Пример 1
    Создание таблицы в новом документе Word со сплошными наружными границами и пунктирными внутри:

    Sub Primer1()

    Dim myWord As New Word.Application, _

    myDocument As Word.Document, myTable As Word.Table

      Set myDocument = myWord.Documents.Add

      myWord.Visible = True

    With myDocument

      Set myTable = .Tables.Add(.Range(0, 0), 5, 4)

    End With

    With myTable

      .Borders.OutsideLineStyle = wdLineStyleSingle

      .Borders.InsideLineStyle = wdLineStyleDot

    End With

    End Sub

    В выражении myDocument.Range(Start:=0, End:=0) ключевые слова Start и End можно не указывать – myDocument.Range(0, 0).

    Пример 2
    Создание таблицы под ранее вставленным заголовком, заполнение ячеек таблицы и применение автосуммы:

    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

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    Sub Primer2()

    On Error GoTo Instr

    Dim myWord As New Word.Application, _

    myDocument As Word.Document, _

    myTable As Word.Table, myInt As Integer

      Set myDocument = myWord.Documents.Add

      myWord.Visible = True

    With myDocument

    ‘Вставляем заголовок таблицы

      .Range.InsertAfter «Продажи фруктов в 2019 году» & vbCr

      myInt = .Range.Characters.Count 1

    ‘Присваиваем заголовку стиль

      .Range(0, myInt).Style = «Заголовок 1»

    ‘Создаем таблицу

      Set myTable = .Tables.Add(.Range(myInt, myInt), 4, 4)

    End With

    With myTable

    ‘Отображаем сетку таблицы

      .Borders.OutsideLineStyle = wdLineStyleSingle

      .Borders.InsideLineStyle = wdLineStyleSingle

    ‘Форматируем первую и четвертую строки

      .Rows(1).Range.Bold = True

      .Rows(4).Range.Bold = True

    ‘Заполняем первый столбец

      .Columns(1).Cells(1).Range = «Наименование»

      .Columns(1).Cells(2).Range = «1 квартал»

      .Columns(1).Cells(3).Range = «2 квартал»

      .Columns(1).Cells(4).Range = «Итого»

    ‘Заполняем второй столбец

      .Columns(2).Cells(1).Range = «Бананы»

      .Columns(2).Cells(2).Range = «550»

      .Columns(2).Cells(3).Range = «490»

      .Columns(2).Cells(4).AutoSum

    ‘Заполняем третий столбец

      .Columns(3).Cells(1).Range = «Лимоны»

      .Columns(3).Cells(2).Range = «280»

      .Columns(3).Cells(3).Range = «310»

      .Columns(3).Cells(4).AutoSum

    ‘Заполняем четвертый столбец

      .Columns(4).Cells(1).Range = «Яблоки»

      .Columns(4).Cells(2).Range = «630»

      .Columns(4).Cells(3).Range = «620»

      .Columns(4).Cells(4).AutoSum

    End With

    ‘Освобождаем переменные

    Set myDocument = Nothing

    Set myWord = Nothing

    ‘Завершаем процедуру

    Exit Sub

    ‘Обработка ошибок

    Instr:

    If Err.Description <> «» Then

      MsgBox «Произошла ошибка: « & Err.Description

    End If

    If Not myWord Is Nothing Then

      myWord.Quit

      Set myDocument = Nothing

      Set myWord = Nothing

    End If

    End Sub

    Метод AutoSum суммирует значения в ячейках одного столбца над ячейкой с суммой. При использовании его для сложения значений ячеек в одной строке, результат может быть непредсказуемым.

    Чтобы просуммировать значения в строке слева от ячейки с суммой, используйте метод Formula объекта Cell:

    myTable.Cell(2, 4).Formula («=SUM(LEFT)»)

    Другие значения метода Formula, применяемые для суммирования значений ячеек:

    • «=SUM(ABOVE)» – сумма значений над ячейкой (аналог метода AutoSum);
    • «=SUM(BELOW)» – сумма значений под ячейкой;
    • «=SUM(RIGHT)» – сумма значений справа от ячейки.


    I wonder if its possible select multiple tables from a word file and sort by a column. Usually I select a table and sort with the option sort by a column, but I have multiples tables in my Word file and I would like use a VBA.

    I am using a macro to select all the tables but the option sort is disabled:

    Sub selecttables()
    Dim mytable As Table
    
    For Each mytable In ActiveDocument.Tables
    mytable.Range.Editors.Add wdEditorEveryone
    Next
    ActiveDocument.SelectAllEditableRanges (wdEditorEveryone)
    ActiveDocument.DeleteAllEditableRanges (wdEditorEveryone)
    End Sub
    

    Please any comment I will grateful

    EDIT

    I woukd like that sort avoid the total row

    Table Example

    asked Jul 15, 2019 at 16:34

    RODRIGO's user avatar

    Using For Each to select each table is the right start. Then sort each table, one at a time, like this example:

        Dim mytable As Table
        For Each mytable In ActiveDocument.Tables
            mytable.Sort ExcludeHeader:=True, FieldNumber:="Column 1", _
                SortFieldType:=wdSortFieldAlphanumeric, SortOrder:=wdSortOrderAscending
        Next
    

    answered Jul 15, 2019 at 22:33

    scenography's user avatar

    scenographyscenography

    3631 gold badge2 silver badges10 bronze badges

    0

    Понравилась статья? Поделить с друзьями:
  • Vba script для excel
  • Vba saveas для word
  • Vba save as word documents
  • Vba runtime error 424 excel
  • Vba rename files excel