Vba как вставить строку в таблицу word

3orP

157 / 2 / 3

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

Сообщений: 26

1

05.07.2013, 12:17. Показов 25301. Ответов 4

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


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

Здравствуйте!

Прошу помочь мне со следующим:

в документе есть 3 таблицы. Во время заполнения 2-ой таблицы из формы нужно сделать так, чтобы при добавлении новой записи создавалась и строчка в которую бы вписывались эти данные
Заранее спасибо!

Вот код, который я сейчас имею:

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
Public i As Integer
 
Private Sub UserForm_Activate()
i = 2
ComboBox1.AddItem "доктора"
ComboBox1.AddItem "кандидата"
ComboBox2.AddItem "архитектуры"
ComboBox2.AddItem "биологических наук"
ComboBox2.AddItem "ветеринарных наук"
End Sub
 
Private Sub CommandButton1_Click()
ActiveDocument.Tables(2).Cell(i, 1).Range = i - 1
ActiveDocument.Tables(2).Cell(i, 2).Range = TextBox1 & ", " & TextBox2 & " // " & TextBox3 & ", " & TextBox4 & "г. №" & TextBox5
i = i + 1
End Sub
 
Private Sub CommandButton4_Click()
ActiveDocument.Tables(2).Cell(i, 1).Range = i - 1
ActiveDocument.Tables(2).Cell(i, 2).Range = TextBox6 & ", " & TextBox7 & ", " & TextBox9 & " г., Электронный доступ: [" & TextBox8 & "]"
i = i + 1
End Sub
 
Private Sub CommandButton6_Click()
ActiveDocument.Tables(2).Cell(i, 1).Range = i - 1
ActiveDocument.Tables(2).Cell(i, 2).Range = TextBox10 & ", " & TextBox11 & ", на соискание степени" & " " & ComboBox1.Text & " " & ComboBox2.Text
i = i + 1
End Sub
 
Private Sub CommandButton8_Click()
ActiveDocument.Tables(2).Cell(i, 1).Range = i - 1
ActiveDocument.Tables(2).Cell(i, 2).Range = TextBox14 & ", " & TextBox15 & " / " & TextBox16 & ", " & TextBox17 & ", " & TextBox18 & " г."
i = i + 1
End Sub



0



S.V.I.N.

5 / 5 / 1

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

Сообщений: 38

16.07.2013, 12:21

2

Уважаемый 3orP,
добавлять новую строку в таблицу можно следующим образом

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
''создаем таблицу
.ActiveDocument.Tables.Add(Range:=.Selection.Range, NumRows:=1, NumColumns:=2)
            With .Selection.Tables(1)
                .Style = "Сетка таблицы"
                .ApplyStyleHeadingRows = True
                .ApplyStyleLastRow = False
                .ApplyStyleFirstColumn = True
                .ApplyStyleLastColumn = False
            End with
''''''''''''
 
'' добавляем новую строку в таблицу, если кол-во строк больше 1. Это условие необходимо для того, что бы
'' при первом прогоне у нас не было пустой строки в таблице
if Selection.Tables(1).Rows.Count <> 1 then
     Selection.InsertRowsBelow 1
end if
'''''''''''
 
'''а далее ваш код
ActiveDocument.Tables(1).Cell(i, 1).Range = i - 1
ActiveDocument.Tables(1).Cell(i, 2).Range = TextBox14 & ", " & TextBox15 & " / " & TextBox16 & ", " & TextBox17 & ", " & TextBox18 & " г."
i = i + 1

Добавлено через 8 минут
небольшая поправка

Visual Basic
1
2
3
4
5
6
'' добавляем новую строку в таблицу, если кол-во строк больше 1. Это условие необходимо для того, что бы
'' при первом прогоне у нас не было пустой строки в таблице
If Selection.Tables(1).Cell(1, 1).Range <> "" Then
     Selection.InsertRowsBelow 1
end if
'''''''''''



1



157 / 2 / 3

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

Сообщений: 26

16.07.2013, 14:05

 [ТС]

3

S.V.I.N., спасибо большое!
а если таблица вот такая и надо вставлять строки перед последней строкой «ИТОГО»?

Вложения

Тип файла: docx п.docx (14.1 Кб, 81 просмотров)



0



S.V.I.N.

5 / 5 / 1

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

Сообщений: 38

16.07.2013, 14:40

4

Т.к. строки нужно вставлять перед последней строкой, то для этого нужно посчитать общее кол-во строк в таблице. Затем из полученного числа вычитаем единичку, т.е. мы получим индекс предпоследней строки таблицы. Далее выделяем предпоследнюю строку и вставляем новую строчку в таблицу…

Visual Basic
1
2
3
4
5
6
7
8
If Selection.Tables(1).Cell(1, 1).Range <> "" Then
 
    ''вот тут мы как раз и вычмсляем предпоследний индекс строки таблицы и выделяем его
    Selection.Tables(1).Rows(Selection.Tables(1).Rows.Count - 1).Select  
    
    ''вставляем новую строчку вниз, после выделенной строки
     Selection.InsertRowsBelow 1
End If



1



157 / 2 / 3

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

Сообщений: 26

16.07.2013, 15:02

 [ТС]

5

S.V.I.N., огромное спасибо!



0



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 Table Insert/Remove Rows/Columns

Aug 26, 2015 in Tables

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:

Word, Table Initial


Delete Row:

The code below will remove the second row of the first table:

Tables.Item(1).Rows(2).Delete

Result:

Word VBA, Delete Row


Delete Column:

The code below will remove the second column of the first table:

Tables.Item(1).Columns(2).Delete

Result:

Word VBA Delete Column


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:

Word VBA Delete 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:
Word VBA insert column

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
enter image description here

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

Понравилась статья? Поделить с друзьями:
  • Vba имя списка excel
  • Vba изменить рисунок excel
  • Vba изменение значений ячеек в excel в одну
  • Vba значение поля word
  • Vba запрет на редактирование ячейки в excel