Microsoft word vba table

title ms.prod ms.assetid ms.date ms.localizationpriority

Working with tables

word

cf0858b7-6b39-4c90-552e-edb695b5cda3

06/08/2019

medium

This topic includes Visual Basic examples related to the tasks identified in the following sections.

Creating a table, inserting text, and applying formatting

The following example inserts a four-column, three-row table at the beginning of the active document. The For Each…Next structure is used to step through each cell in the table. Within the For Each…Next structure, the InsertAfter method of the Range object is used to add text to the table cells (Cell 1, Cell 2, and so on).

Sub CreateNewTable() 
 Dim docActive As Document 
 Dim tblNew As Table 
 Dim celTable As Cell 
 Dim intCount As Integer 
 
 Set docActive = ActiveDocument 
 Set tblNew = docActive.Tables.Add( _ 
 Range:=docActive.Range(Start:=0, End:=0), NumRows:=3, _ 
 NumColumns:=4) 
 intCount = 1 
 
 For Each celTable In tblNew.Range.Cells 
  celTable.Range.InsertAfter "Cell " & intCount 
  intCount = intCount + 1 
 Next celTable 
 
 tblNew.AutoFormat Format:=wdTableFormatColorful2, _ 
 ApplyBorders:=True, ApplyFont:=True, ApplyColor:=True 
End Sub

Inserting text into a table cell

The following example inserts text into the first cell of the first table in the active document. The Cell method returns a single Cell object. The Range property returns a Range object. The Delete method is used to delete the existing text and the InsertAfter method inserts the «Cell 1,1» text.

Sub InsertTextInCell() 
 If ActiveDocument.Tables.Count >= 1 Then 
  With ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Range 
   .Delete 
   .InsertAfter Text:="Cell 1,1" 
  End With 
 End If 
End Sub

Returning text from a table cell without returning the end of cell marker

The following example returns and displays the contents of each cell in the first row of the first document table.

Sub ReturnTableText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
  Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _ 
  End:=celTable.Range.End - 1) 
  MsgBox rngTable.Text 
 Next celTable 
End Sub
Sub ReturnCellText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
  Set rngTable = celTable.Range 
  rngTable.MoveEnd Unit:=wdCharacter, Count:=-1 
  MsgBox rngTable.Text 
 Next celTable 
End Sub

Converting existing text to a table

The following example inserts tab-delimited text at the beginning of the active document and then converts the text to a table.

Sub ConvertExistingText() 
 With Documents.Add.Content 
  .InsertBefore "one" & vbTab & "two" & vbTab & "three" & vbCr 
  .ConvertToTable Separator:=Chr(9), NumRows:=1, NumColumns:=3 
 End With 
End Sub

Returning the contents of each table cell

The following example defines an array equal to the number of cells in the first document table (assuming Option Base 1). The For Each…Next structure is used to return the contents of each table cell and assign the text to the corresponding array element.

Sub ReturnCellContentsToArray() 
 Dim intCells As Integer 
 Dim celTable As Cell 
 Dim strCells() As String 
 Dim intCount As Integer 
 Dim rngText As Range 
 
 If ActiveDocument.Tables.Count >= 1 Then 
  With ActiveDocument.Tables(1).Range 
   intCells = .Cells.Count 
   ReDim strCells(intCells) 
   intCount = 1 
   For Each celTable In .Cells 
    Set rngText = celTable.Range 
    rngText.MoveEnd Unit:=wdCharacter, Count:=-1 
    strCells(intCount) = rngText 
    intCount = intCount + 1 
   Next celTable 
  End With 
 End If 
End Sub

Copying all tables in the active document into a new document

This example copies the tables from the current document into a new document.

Sub CopyTablesToNewDoc() 
 Dim docOld As Document 
 Dim rngDoc As Range 
 Dim tblDoc As Table 
 
 If ActiveDocument.Tables.Count >= 1 Then 
  Set docOld = ActiveDocument 
  Set rngDoc = Documents.Add.Range(Start:=0, End:=0) 
  For Each tblDoc In docOld.Tables 
   tblDoc.Range.Copy 
   With rngDoc 
    .Paste 
    .Collapse Direction:=wdCollapseEnd 
    .InsertParagraphAfter 
    .Collapse Direction:=wdCollapseEnd 
   End With 
  Next 
 End If 
End Sub

[!includeSupport and feedback]

Создание таблиц в документе 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)» – сумма значений справа от ячейки.


TablesTable
Multiple objects

Represents a single table. The Table object is a member of the Tables
collection. The Tables collection includes all the tables in the specified selection, range, or document.

Using the Table Object

Use Tables(index), where index is the index number, to return a single Table object. The index number represents the position of the table in the selection, range, or document. The following example converts the first table in the active document to text.

ActiveDocument.Tables(1).ConvertToText Separator:=wdSeparateByTabs
		

Use the Add
method to add a table at the specified range. The following example adds a 3×4 table at the beginning of the active document.

Set myRange = ActiveDocument.Range(Start:=0, End:=0)
ActiveDocument.Tables.Add Range:=myRange, NumRows:=3, NumColumns:=4
		

Table

Microsoft Word VBA offers very powerful object called Table and a collection Tables as part of a Document Object. Table is very useful to populate account, time table, categorization of objects etc. Tables is a collection which can have many nested tables and can be iterated using for each loop. It allows developer to manipulate all the properties during development of a table in a document like formatting, rows, columns, borders, cells, range, size, width, height etc. Latest office release provides more robust and enrich properties to the table object.

Code example

Public Sub CreateTable()
    Dim oDoc As Document
    Set oDoc = ActiveDocument
    Dim oTable As Table
    Set oTable = oDoc.Tables.Add(Range:=oDoc.Range(Start:=0, End:=0), NumRows:=3, NumColumns:=3)
    Set oTable = Nothing
End Sub

This code will create a table of 3×3 but table will not have borders and will not be visible on the document but you can see at the starting of document the table is inserted. To prove I have given it border so you can see the real output:

Let’s insert some values in table by extending existing code:

Code example

Public Sub CreateAndInsertValuesInTable()
    Dim oDoc As Document
    Set oDoc = ActiveDocument
    Dim oTable As Table
    Dim oCel As Cell
    Dim oCounter As Integer
    oCounter = 1
    Set oTable = oDoc.Tables.Add(Range:=oDoc.Range(Start:=0, End:=0), NumRows:=3, NumColumns:=3)
    'Adding value in each cell
    For Each oCel In oTable.Range.Cells
        oCel.Range.InsertAfter "Cell number: " & oCounter
        oCounter = oCounter + 1
    Next oCel
    Set oTable = Nothing
End Sub

Output

Now let’s format the table in real beautiful colors and patterns:

Code example

Public Sub CreateTableAndFormat()
    Dim oDoc As Document
    Set oDoc = ActiveDocument
    Dim oTable As Table
    Dim oCel As Cell
    Dim oCounter As Integer
    oCounter = 1
    Set oTable = oDoc.Tables.Add(Range:=oDoc.Range(Start:=0, End:=0), NumRows:=3, NumColumns:=3)
    'Adding value in each cell
    For Each oCel In oTable.Range.Cells
        oCel.Range.InsertAfter "Cell number: " & oCounter
        oCounter = oCounter + 1
    Next oCel
    'Auto format table
    oTable.AutoFormat Format:=wdTableFormatColorful3, ApplyBorders:=True, ApplyFont:=True, ApplyColor:=True
    Set oCel = Nothing
    Set oTable = Nothing
End Sub

Output

Iterate tables

Public Sub IteratingAllTablesInActiveDoc()
    Dim oDoc As Document
    Set oDoc = ActiveDocument
    Dim oTable As Table
    'Avialbe tables in active document
    Debug.Print "Total tables in Active Document : " & oDoc.Tables.Count
    For Each oTable In oDoc.Tables
        'Do whatever you want here
    Next oTable
	Set oTable=Nothing
End Sub

Text to table

Sub ConvertExistingTextToTable()
	With Documents.Add.Content
		.InsertBefore "one" & vbTab & "two" & vbTab & "three" & vbCr
		.ConvertToTable Separator:=Chr(9), NumRows:=1, NumColumns:=3
	End With
End Sub

Nested table

Another challenge of reading a table which is created or available inside a table. Microsoft Word supports nested table concept but this scenario a bit different and challenging to the developer where he may need to write code to trap a table available inside Cell.

Code example

Public Sub ReadNestedTableWithinCell()
    Dim parentTable As Table
    Dim childTable As Table
    Dim oCell As Cell
    'Set Parent Table object
    Set parentTable = ActiveDocument.Tables(1)
    'Set Cell Reference of parent table of row 2 and cell 1 where nested table is
    Set oCell = parentTable.Rows(2).Cells(1)
    'Check if cell contains a table
    If oCell.Tables.Count > 0 Then
        'Get Child Table available inside cell
        Set childTable = oCell.Tables(1)
		childTable.Select
    End If
End Sub

Output

Next : Bookmark Object in Word VBA

Понравилась статья? Поделить с друзьями:
  • Microsoft word use in business
  • Microsoft word underline word
  • Microsoft word ultimate скачать
  • Microsoft word uchun translit dasturi скачать
  • Microsoft word torrents for windows 10