Vba вставка текста в таблицу word

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]

goscomment

0 / 0 / 0

Регистрация: 25.05.2017

Сообщений: 9

1

25.05.2017, 15:45. Показов 10791. Ответов 2

Метки нет (Все метки)


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

Добрый день, ребята выручайте! Часа 3 пытаюсь найти не получается.

Задача — есть таблица word, нужно вставить текст в каждую пустую ячейку этой таблицы.

Нашел такой макрос, он мне подходит, но вместо вставки текста он раскрашивает, помогите исправить это

Visual Basic
1
2
3
4
5
6
7
8
Sub ColorOfEmptyCells()
Dim oCell As Cell
For Each oCell In Selection.Tables(1).Range.Cells
    If oCell.Range.Characters.Count = 1 Then
         oCell.Shading.BackgroundPatternColor = wdColorGray50
    End If
Next
End Sub



0



shanemac51

Модератор

Эксперт MS Access

11341 / 4660 / 748

Регистрация: 07.08.2010

Сообщений: 13,497

Записей в блоге: 4

25.05.2017, 15:52

2

Лучший ответ Сообщение было отмечено goscomment как решение

Решение

попробуйте

Visual Basic
1
2
3
4
5
6
7
8
Sub ColorOfEmptyCells()
Dim oCell As Cell
For Each oCell In Selection.Tables(1).Range.Cells
    If oCell.Range.Characters.Count <=2 Then
         oCell.range.text="mmm"
    End If
Next
End Sub



1



0 / 0 / 0

Регистрация: 25.05.2017

Сообщений: 9

25.05.2017, 15:53

 [ТС]

3

Работает, спасибо!))))))



0



Формулировка задачи:

Добрый день. Ломаю голову над казалось бы элементарной задачей. В документе Word существует таблица, уже сформатированная должным образом. В нее необходимо выгружать данные с листа Excel. Копирование / вставка из ячеек проходит,

но мне при этом нужно добавлять строки в середине таблицы в Worde

.
Делаю так

пробовала

Код к задаче: «Вставка строки в уже существующую таблицу в Word»

textual

Dim tblNew As Table
Dim rowNew As Row
 
Set tblNew = ActiveDocument.Tables(2)
'вставка перед 2ой строкой
Set rowNew = tblNew.Rows.Add(BeforeRow:=tblNew.Rows(2))

Полезно ли:

12   голосов , оценка 3.833 из 5

Редактирование документов Word из кода VBA Excel. Добавление и форматирование текста. Объект Word.Range, свойство Text, методы InsertAfter и InsertBefore.

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

Добавление текста в новый документ

Основные объекты, использующиеся в VBA Word для определения места вставки, добавления и форматирования текста – это Selection (выделение), Range (диапазон) и Bookmark (закладка).

Selection и Range позволяют заполнять текстом новые документы или редактировать существующие. Закладки можно использовать для вставки изменяемых реквизитов в шаблоны различных документов: договоры, акты, справки.

Объект Range имеет преимущество перед объектом Selection, так как он может быть создан только программно и не зависит от действий пользователя. Если для вставки и форматирования текста будет использоваться объект Selection, а пользователь во время работы программы просто поставит курсор в другое место документа, результат будет непредсказуем.

Word.Range кардинально отличается от объекта Range в Excel. В приложении Word он представляет из себя набор из одного или множества символов. А также он может вообще не содержать ни одного символа, а быть указателем ввода текста (виртуальным курсором).

Объект Range возвращается свойством Range других объектов приложения Word: Document, Selection, Bookmark, Paragraph, Cell (объект Table).

Вставка текста без форматирования

Если текст вставляется без форматирования, достаточно одной строки кода (myDocument – это переменная):

  • Вставка текста с заменой имеющегося: myDocument.Range.Text = "Вставляемый текст"
  • Добавление текста после имеющегося: myDocument.Range.InsertAfter "Добавляемый текст"
  • Добавление текста перед имеющимся: myDocument.Range.InsertBefore "Добавляемый текст"

Методами InsertAfter и InsertBefore можно вставить текст и на пустую страницу, также, как с помощью свойства Text. Перейти на новый абзац и начать предложение с красной строки можно с помощью ключевых слов vbCr (vbNewLine, vbCrLf) и vbTab.

Вставка текста с форматированием

Для форматирования отдельных участков текста необходимо указать диапазон символов, входящих в этот участок. Здесь нам также поможет объект Range, которому можно задать любой набор символов, содержащихся в документе Word.

Синтаксис присвоения диапазона символов объекту Range:

myDocument.Range(Start:=n, End:=m)

‘или без ключевых слов Start и End

myDocument.Range(n, m)

  • myDocument – переменная;
  • n – номер точки перед начальным символом;
  • m – номер точки после конечного символа.

Счет точек вставки начинается с нуля. Знаки переноса строки, возврата каретки и табуляции учитываются как отдельные символы. 0 – это для объекта Word.Range виртуальная точка вставки на пустом документе, 1 – точка между первым и вторым символом, 2 – точка между вторым и третьим символом и т.д.

На пустом документе объекту Range можно присвоить только виртуальную точку вставки:
myDocument.Range(Start:=0, End:=0)

Первый символ в документе с текстом:
myDocument.Range(Start:=0, End:=1)

Диапазон с 11 по 20 символ:
myDocument.Range(Start:=10, End:=20)

Реальная точка вставки (курсор) принадлежит объекту Selection, который создается вручную или программно с помощью метода Select.

Вставка курсора в начало документа:
myDocument.Range(Start:=0, End:=0).Select

Эта строка вставит курсор между пятым и шестым символами:
myDocument.Range(Start:=5, End:=5).Select

Вставка курсора в конец документа:
myDocument.Range(.Range.Characters.Count - 1, .Range.Characters.Count - 1).Select

Ссылку на объект Range можно присвоить переменной, но при форматировании ее придется каждый раз переопределять и код получится длиннее. Пример присвоения ссылки объектной переменной:

Dim myRange As Word.Range

Set myRange = myDocument.Range(Start:=0, End:=20)

Для Range(Start:=0, End:=20) в документе должно быть как минимум 20 символов.

Однострочные примеры редактирования и форматирования текста

Вставка дополнительного текста внутри имеющегося после заданной точки:
myDocument.Range(Start:=10, End:=10).InsertAfter "Вставляемый текст"

Новый абзац с красной строки (предыдущая строка должна заканчиваться символом возврата каретки или переноса строки):
myDocument.Range.InsertAfter vbTab & "Красная строка"

Присвоение шрифту заданного диапазона зеленого цвета:
myDocument.Range(Start:=10, End:=65).Font.ColorIndex = wdGreen

Меняем обычное начертание на курсив:
myDocument.Range(Start:=10, End:=65).Font.Italic = True

Указываем размер шрифта:
myDocument.Range(Start:=10, End:=65).Font.Size = 22

Применение стандартных стилей:
myDocument.Range(Start:=0, End:=16).Style = "Заголовок 1"

Если вас заинтересуют другие команды форматирования текста, запишите их макрорекордером в VBA Word и примените к объекту Range.

Пример 1
Добавление текста в новый документ без форматирования:

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

Sub Primer1()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document

Set myDocument = myWord.Documents.Add

myWord.Visible = True

With myDocument

.Range.Text = «Заголовок по центру» & vbCr

.Range(Start:=0, End:=19).ParagraphFormat.Alignment _

  = wdAlignParagraphCenter

.Range.InsertAfter _

  vbTab & «Первый абзац с красной строки» & vbCr & _

  «Второй абзац не с красной строки» & vbCr & _

  vbTab & «Третий абзац с красной строки»

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

Пример 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

Sub Primer2()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document

Set myDocument = myWord.Documents.Add

myWord.Visible = True

With myDocument

.Range.Text = «Заголовок по центру» & vbCr

.Range(Start:=0, End:=19).Style = «Заголовок»

.Range(Start:=0, End:=19).ParagraphFormat.Alignment _

  = wdAlignParagraphCenter

.Range.InsertAfter «Заголовок 1 не по центру» & vbCr

.Range(Start:=20, End:=44).Style = «Заголовок 1»

.Range.InsertAfter vbTab & «Шрифт по умолчанию « _

  & «с красной строки» & vbCr

.Range.InsertAfter «Зеленый курсив, размер 20»

.Range(Start:=82, End:=107).Font.Italic = True

.Range(Start:=82, End:=107).Font.Size = 20

.Range(Start:=82, End:=107).Font.ColorIndex = wdGreen

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

Вы можете запустить эти примеры в редакторе VBA Excel на своем компьютере и посмотреть результаты.

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

Rows.Add method (Word)

vbawd10.chm155975780

vbawd10.chm155975780

word

Word.Rows.Add

d84286cb-42b5-a717-f152-0d9c3f1c6d9c

06/08/2017

medium

Rows.Add method (Word)

Returns a Row object that represents a row added to a table.

Syntax

expression.Add ( _BeforeRow_ )

expression Required. A variable that represents a Rows object.

Parameters

Name Required/Optional Data type Description
BeforeRow Optional Variant A Row object that represents the row that will appear immediately below the new row.

Return value

Row

Example

This example inserts a new row before the first row in the selection.

Sub AddARow() 
 If Selection.Information(wdWithInTable) = True Then 
 Selection.Rows.Add BeforeRow:=Selection.Rows(1) 
 End If 
End Sub

This example adds a row to the first table and then inserts the text Cell into this row.

Sub CountCells() 
 Dim tblNew As Table 
 Dim rowNew As Row 
 Dim celTable As Cell 
 Dim intCount As Integer 
 
 intCount = 1 
 Set tblNew = ActiveDocument.Tables(1) 
 Set rowNew = tblNew.Rows.Add(BeforeRow:=tblNew.Rows(1)) 
 For Each celTable In rowNew.Cells 
 celTable.Range.InsertAfter Text:="Cell " & intCount 
 intCount = intCount + 1 
 Next celTable 
End Sub

See also

Rows Collection Object

[!includeSupport and feedback]

Понравилась статья? Поделить с друзьями:
  • Vba вставить разрыв страницы word
  • Vba word цвет шрифта
  • Vba время в формате excel
  • Vba word цвет фона
  • Vba включить макрос excel