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]
3orP 157 / 2 / 3 Регистрация: 27.12.2012 Сообщений: 26 |
||||
1 |
||||
05.07.2013, 12:17. Показов 25301. Ответов 4 Метки нет (Все метки)
Здравствуйте! Прошу помочь мне со следующим: в документе есть 3 таблицы. Во время заполнения 2-ой таблицы из формы нужно сделать так, чтобы при добавлении новой записи создавалась и строчка в которую бы вписывались эти данные Вот код, который я сейчас имею:
0 |
S.V.I.N. 5 / 5 / 1 Регистрация: 06.04.2012 Сообщений: 38 |
||||||||
16.07.2013, 12:21 |
2 |
|||||||
Уважаемый 3orP,
Добавлено через 8 минут
1 |
157 / 2 / 3 Регистрация: 27.12.2012 Сообщений: 26 |
||
16.07.2013, 14:05 [ТС] |
3 |
|
S.V.I.N., спасибо большое! Вложения
0 |
S.V.I.N. 5 / 5 / 1 Регистрация: 06.04.2012 Сообщений: 38 |
||||
16.07.2013, 14:40 |
4 |
|||
Т.к. строки нужно вставлять перед последней строкой, то для этого нужно посчитать общее кол-во строк в таблице. Затем из полученного числа вычитаем единичку, т.е. мы получим индекс предпоследней строки таблицы. Далее выделяем предпоследнюю строку и вставляем новую строчку в таблицу…
1 |
157 / 2 / 3 Регистрация: 27.12.2012 Сообщений: 26 |
|
16.07.2013, 15:02 [ТС] |
5 |
S.V.I.N., огромное спасибо!
0 |
VBA, Word Table Insert/Remove Rows/Columns
In this article I will explain how you can add and delete rows and columns from tables in a word document using VBA.
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:
–
Delete Row:
The code below will remove the second row of the first table:
Tables.Item(1).Rows(2).Delete
Result:
–
Delete Column:
The code below will remove the second column of the first table:
Tables.Item(1).Columns(2).Delete
Result:
–
Insert Row:
The codes below will all insert an empty row after the first row:
Tables.Item(1).Rows.Add (Tables.Item(1).Rows.Item(2))
Tables.Item(1).Rows(1).Select
Selection.InsertRowsBelow (1)
Tables.Item(1).Rows(2).Select
Selection.InsertRowsAbove (1)
The Rows.Add gets as input a row object. The new row will be inserted before the input row. The function Selection.InsertRowsBelow inserts as many rows passed as the input parameter below the currently selected row.
Result:
–
Insert Columns:
I find the column insertion methods a bit awkward. While there were 3 methods for inserting rows there are only 2 methods for inserting columns:
Tables.Item(1).Columns(1).Select
Selection.InsertColumnsRight
Tables.Item(1).Columns(2).Select
Selection.InsertColumns
The first method inserts a column to the right of the selected column. The second inserts a column to the left of the selected column.
Result:
You can download the file and code related to this article from the link below:
- Row Columns.docm
See also:
- Word VBA, Modify Table Data
- Word VBA Resize Table Columns and Rows
- Word VBA, Delete Empty Rows From Tables
- Inserting rows using Excel VBA
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com
Working with merged rows in MS Word Table is slightly tricky.
Is this what you want?
Sub Sample()
Dim CurrentTable As Table
Dim wdDoc As Document
Dim Rw As Long, col As Long
Set wdDoc = ActiveDocument '<~~ Created this for testing
Set CurrentTable = wdDoc.Tables(1)
Rw = 9: col = CurrentTable.Columns.Count
wdDoc.Range(CurrentTable.Cell(Rw, 1).Range.Start, _
CurrentTable.Cell(Rw, col).Range.Start).Select
wdDoc.Application.Selection.InsertRowsBelow
End Sub
ScreenShot
Edit
You table’s format is all screwed up. Table was created with few rows and then the cells were merged/split to create new rows and hence you were getting the error. Also since you are automating word from excel, I would recommend the following way.
Try this
Sub WordTableTester()
Dim oWordApp As Object, oWordDoc As Object, CurrentTable As Object
Dim flName As Variant
Dim Rw As Long, col As Long
flName = Application.GetOpenFilename("Word files (*.docx),*.docx", _
, "Please choose a file containing requirements to be imported")
If flName = False Then Exit Sub
Set oWordApp = CreateObject("Word.Application")
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Open(flName)
Set CurrentTable = oWordDoc.Tables(1)
Rw = 7: col = CurrentTable.Columns.Count
oWordDoc.Range(CurrentTable.Cell(Rw, 1).Range.Start, _
CurrentTable.Cell(Rw, col).Range.Start).Select
oWordDoc.Application.Selection.InsertRowsBelow
End Sub
Формулировка задачи:
Добрый день. Ломаю голову над казалось бы элементарной задачей. В документе 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