Как удалить строку в таблице word vba

0 / 0 / 0

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

Сообщений: 5

1

Word

01.11.2019, 09:31. Показов 12044. Ответов 9


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

Здравствуйте!
По работе необходимо подготовить к распечатке множество документов в каждом из котором имеются таблицы между которыми различный текст включая рисунки, при этом строки в которых имеется ячейка со значение #N/A нужно удалить из всех таблиц. Хочу записать макрос для этой цели, вот только своей головы не хватает.
Помогите, пожалуйста, кто знает.
Заранее благодарен.



0



Остап Бонд

Заблокирован

01.11.2019, 09:39

2

Klerkof, приложите к сообщению такой документ, тем самым многократно увеличив свои шансы на получение помощи.



0



Модератор

Эксперт MS Access

11342 / 4661 / 748

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

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

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

01.11.2019, 09:59

3

Цитата
Сообщение от Klerkof
Посмотреть сообщение

имеется ячейка со значение #N/A нужно удалить из всех таблиц

имеются ли в таблицах объединенные ячейки



0



0 / 0 / 0

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

Сообщений: 5

01.11.2019, 10:47

 [ТС]

4

Обьединенные ячейки имеются в двух первых строках, но их редактировать не надо, так как это названия столбцов



0



0 / 0 / 0

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

Сообщений: 5

01.11.2019, 11:06

 [ТС]

5

Вот пример файла:
первая страница — как есть;
вторая страница — как надо



0



Модератор

Эксперт MS Access

11342 / 4661 / 748

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

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

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

01.11.2019, 11:45

6

Цитата
Сообщение от Klerkof
Посмотреть сообщение

Вот пример файла:

ваш пример не имеет объединенных ячеек — это противоречит вам же



0



0 / 0 / 0

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

Сообщений: 5

01.11.2019, 11:57

 [ТС]

7

Цитата
Сообщение от shanemac51
Посмотреть сообщение

ваш пример не имеет объединенных ячеек — это противоречит вам же

это не принципиально, их можно будет разделить и ничего не потеряем



0



shanemac51

Модератор

Эксперт MS Access

11342 / 4661 / 748

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

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

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

01.11.2019, 12:17

8

ПОПРОБУЙТЕ КОД(на копии конечно)
т3-работает
т2- некорректно работает
т1- не работает

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
Sub a_________mm191101_table()
'
Dim tbl As Table
Dim r1, r1k, c1, c1k
On Error Resume Next
For Each tbl In Word.ActiveDocument.Tables
r1k = tbl.Rows.Count
c1k = tbl.Columns.Count
Debug.Print r1k, c1k
 
Do While r1k > 1
 
For c1 = 1 To c1k
''Debug.Print tbl.Range.Rows(r1k).Range.Cells(c1).Range.Text;
If tbl.Range.Rows(r1k).Cells(c1).Range.Text Like "[#]N/A*" Then
tbl.Range.Rows(r1k).Delete
Exit For
End If
Next c1
 
r1k = r1k - 1
Loop
Next tbl
 
End Sub

Миниатюры

Удаления строк в таблице Word по условию
 

Вложения

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



0



Narimanych

2630 / 1636 / 744

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

Сообщений: 5,143

01.11.2019, 19:07

9

Klerkof,

Попробуйте как вариант

Visual Basic
1
2
3
4
5
6
7
SUB MMM()
For i = 1 To Word.ActiveDocument.Tables.Count
   For Each C In ActiveDocument.Tables(i).Range.Cells
   If C.Range.Text Like "*[#]N/A*" Then C.Range.Rows.Delete
   Next 
Next
End Sub



1



0 / 0 / 0

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

Сообщений: 5

05.11.2019, 05:06

 [ТС]

10

Работает, огромное спасибо)

Добавлено через 1 час 6 минут
только пришлось добавить
Option Compare Binary



0



Sub Макрос()

    Dim tbl As Table, i As Long

            ‘1. Отключение монитора (может это ускорит макрос и не будет мерцать).
    Application.ScreenUpdating = False

        ‘2. Присваиваем таблице имя «tbl».
    Set tbl = ActiveDocument.Tables(1)

        ‘3. Цикл по строкам таблицы с последней по четвёртую.
    For i = tbl.Rows.Count To 4 Step -1
        ‘ Если в текущей ячейке в столбце 1 текст «Начало», то удалить строку.
            ‘ В ворде, в конце каждой ячейки есть два символа. Один символ в виде кружка,
            ‘ второй символ вообще не видно, но VBA его видит.
        If tbl.Cell(i, 1).Range.Text = «Начало» & Chr(13) & Chr(7) Then
            tbl.Rows(i).Delete
        End If
    Next i

        ‘4. Вкл. монитора.
    Application.ScreenUpdating = True

        ‘5. Сообщение.
    MsgBox «Готово.», vbInformation

End Sub

[свернуть]

The following code successfully deletes the selection in a table.

If Selection.Information(wdWithInTable) Then
    Selection.Rows.Delete
End If

Furthermore, the following code successfully prevents the first two table rows from deletion but deletes from the bottom row up not based on selection.

Dim index As Long
    For index = ActiveDocument.Tables(1).Rows.Count To 3 Step -1
        ActiveDocument.Tables(1).Rows(index).Delete
    Exit For
    Next index

Is there a way to combine the two so I can delete any selected row but prevent the first two rows from deletion?

asked Dec 4, 2020 at 20:10

Mohamad Bachrouche's user avatar

3

It would be helpful if you stated clearly what you’re trying to achieve. Try something along the lines of:

Sub Demo()
With Selection
  If .Information(wdWithInTable) = False Then Exit Sub
  If .Cells(.Cells.Count).RowIndex > 2 Then
    If .Cells(1).RowIndex < 3 Then
      .Start = .Tables(1).Rows(3).Range.Start
    End If
    .Rows.Delete
  End If
End With
End Sub

answered Dec 6, 2020 at 19:46

macropod's user avatar

macropodmacropod

12.6k2 gold badges9 silver badges21 bronze badges

3

Добрый день, существует макрос
[vba]

Код

Option Explicit
Dim myDocument As Word.Document

Sub cardWord()
    Dim myWord As New Word.Application
    Dim n As Integer
    On Error GoTo InStr
    Set myDocument = myWord.Documents.Open(ThisWorkbook.Path & «/DocWord.doc»)

            For n = 0 To 10
        myDocument.Content.Find.Execute «Товар_» & CStr(n), False, False, False, False, False, True, 1, False, «ТОВАР №» & CStr(n), 2
    Next

                ‘Сохранение перед закрытием
    myDocument.SaveAs (ThisWorkbook.Path & «/Измененная карта_карта.doc»)
    myDocument.Close

        ‘myDocument.Close ‘Был отключен
    myWord.Quit
Exit Sub

    ‘Обработчик ошибок
InStr:
    If Err.Description <> «» Then
        MsgBox «Ошибка » & Err.Description
        myDocument.Close
        myWord.Quit
    End If
End Sub

[/vba]
Также существует файл Word с таблицей. Задача состоит в том, чтобы сделать так чтобы программа добавили строки в таблицу или удалила если необходимо в зависимости от изменения n.
То есть если товаров 100, то они должны быть в таблице, если 2 тоже должны быть в таблице, но в первом случае в таблице программным образом установить 100 строк, во втором 2. Спасибо

This article shows how to use VBA in MS Word to delete empty rows from a table or rows that have at least one cell that is empty. Say you have multiple tables in a Word document and you want to print the document with only the non-empty rows. Or the tables are to be imported into a database in which the values cannot be blank. These are just some of the scenarios where you will find a practical implementation of this code.

Before we jump into the examples, let us look at two different ways to access a table in a Word document.

1. By using the table index. Below code sets the Tbl variable to the second table in the document.

Set Tbl = ThisDocument.Tables(2)

2. By using the table title. You can set the title by selecting a table in word > Right Click > Table Properties > Alt Text tab

You can loop through all the tables in the document and check for the title to update only those tables that specify a certain condition:

For Each Tbl In ThisDocument.Tables
        If InStr(1, Tbl.Title, "Invoices") = 1 Then
    	'Your code goes here
        End If
Next Tbl

So, the code will be executed for all the tables that have title starting with invoices.

Example 1: Delete rows that are completely blank

For each row, the code checks the length of the row and if it is equal to the length of a blank row, it is deleted.
Note that we start from the bottom-most row and move to the top (because the row index will change if we start deleting from the top).

Set Tbl = ThisDocument.Tables(1)
        With Tbl
            noOfCol = Tbl.Range.Rows(1).Cells.Count
            For i = .Rows.Count To 1 Step -1
                With .Rows(i)
                    If Len(.Range) = noOfCol * 2 + 2 Then .Delete
                End With
            Next i

Here, the “Table.Range” property returns a Range object that represents the portion of a document that is contained within the specified table.

.Rows(1) returns the first row of the table

.Cells returns the cells in the selected row

.Count gives the number of cells in the row (i.e. number of columns in the table)

.Delete deletes a row

A point to be noted here is that the length of each blank cell in the table is 2. And if you have any text in the cell, the length of the cell equals length of the string + 2. For example, if a cell contains text “Word”, length of the cell is 6 (4 + 2)

Also, the length of the end of row character is also 2. So, length of a blank row equals 2* + 2

Example 2: Delete rows that contain at least one cell blank

Here the loop iterates through each cell in the table and if the length is equal to 2 (i.e. the cell is empty), the entire row is deleted. This example and the next one use the Mod operator.

        Set Tbl = ThisDocument.Tables(1)
        With Tbl
            noOfCol = Tbl.Range.Rows(1).Cells.Count
            With .Range
                For i = .Cells.Count To 1 Step -1
                    On Error Resume Next
                    If Len(.Cells(i).Range) = 2 Then
                        .Rows(.Cells(i).RowIndex).Delete
                        j = i Mod noOfCol
                        If j = 0 Then j = noOfCol
                        i = i – j
                    End If
                Next i
        End With

Note that “j” is used here to adjust the value of “i” to the row above the deleted row (to reduce the number of executions of the loop). If your table consists of merged cells, it is better to remove the three lines after the delete row function as it will cause errors in the output.

Consider a table that has three header rows with blanks in them:

The first 3 lines consist of the headers and obviously we do not intend to delete them even if there are blanks present. So, we modify the above code to accommodate for the first three header rows. Here is the entire code:

Sub DeleteEmptyTableRows()
    Application.ScreenUpdating = False
    Dim Tbl As Table
    Dim i As Long
    Dim noOfCol As Integer, j As Integer

    For Each Tbl In ThisDocument.Tables
        With Tbl
            noOfCol = Tbl.Range.Rows(2).Cells.Count

            For i = .Rows.Count To 4 Step -1
                With .Rows(i)
                    If Len(.Range) = noOfCol * 2 + 2 Then .Delete
                End With
            Next i
            With .Range
                For i = .Cells.Count To noOfCol * 3 + 1 Step -1
                    On Error Resume Next
                    If Len(.Cells(i).Range) = 2 Then
                        .Rows(.Cells(i).RowIndex).Delete
                        j = i Mod noOfCol
                        If j = 0 Then j = noOfCol
                        i = i - j
                    End If
                Next i
            End With
        End With
    Next Tbl
    Set Tbl = Nothing
    Application.ScreenUpdating = True
End Sub

Things to note:
– The first row consists of merged cells. So, we have used the second row to get the number of columns in the table
– The first for loop that checks for an entire empty row goes from the last row to row number 4
– For the second for loop that checks each cell, the counter ends at the first cell of the fourth row
– I have used both the for loops just to demonstrate how to take care of headers in both the examples. You can choose which one to use based on your requirement.

After you run the code, the table will look like this:

See also:

  • Deleting rows using Excel VBA

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как удалить строку в таблице excel чтобы не нарушить формулу
  • Как удалить строку в таблице excel чтобы не нарушить нумерацию
  • Как удалить строку в таблице excel через одну
  • Как удалить строку в excel комбинацией клавиш
  • Как удалить строку в таблице excel формула

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии