Vba word удалить столбец таблицы

I have a long macro that jumps to different bookmarks and deletes columns from the selected tables.
Here is an example from my macro:

If ActiveDocument.Bookmarks.Exists("ProposedOverallObj") = True Then
ActiveDocument.Bookmarks.Item("ProposedOverallObj").Select
Call ApproveProposedOverallObj
End If

and then the macro that that calls is:

Sub ApproveProposedOverallObj()

Selection.Cut
Selection.GoTo What:=wdGoToBookmark, Name:="Objectives"
With ActiveDocument.Bookmarks
    .DefaultSorting = wdSortByName
    .ShowHidden = False
End With
Selection.PasteAndFormat (wdPasteDefault)
Selection.Tables(1).Columns(5).Delete
Selection.Tables(1).Columns(4).Delete
Selection.Tables(1).Columns(3).Delete
Selection.Tables(1).Columns(2).SetWidth ColumnWidth:=600.5, RulerStyle:= _
    wdAdjustFirstColumn
End If
End Sub 

Sometimes these run ok, and sometimes they bug out and I get an error:

«Run-time error ‘5825’: Object has been deleted.

Basically it deletes columns 5 and 3 and then bugs and says «I can’t delete column 3 because it has been deleted» but…it hasn’t. Column 3 is still very much there.

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

Как удалить все пустые строки и столбцы из таблиц в Word? В этом руководстве показано несколько способов удаления пустых строк и столбцов из таблиц в документе Word.

Вручную удалить все пустые строки и столбцы из таблиц

Удалите все пустые строки и столбцы из таблиц с помощью кода VBA

Удалите все пустые строки и столбцы из таблиц одним щелчком мышихорошая идея3


Вручную удалить все пустые строки и столбцы из таблиц

Microsoft Office Word не предоставляет удобный способ удаления пустых строк и столбцов, и вам необходимо удалить их, вручную выбрав каждую пустую строку и столбец, а затем удаляя их по одному.

Шаг 1: Выберите пустую строку или пустой столбец, который вы хотите удалить. Смотрите скриншот:

doc-removerowsandcols-1

Шаг 3: Под Настольные Инструменты, щелкните значок макет вкладка;

doc-removerowsandcols-2

Шаг 4: в Строки и столбцы группу, нажмите Удалить строки или Удалить столбцы.

doc-removerowsandcols-3


Удалите все пустые строки и столбцы из таблиц с помощью кода VBA

Макрофункция Word предоставляет гораздо более удобный способ удалить все пустые строки и столбцы из таблиц в документе. Вы можете удалить все пустые строки и столбцы следующим образом.

Шаг 1: нажмите «Alt-F11» открыть окно Microsoft Visual Basic для приложений;

Шаг 2: нажмите Модули на Вставить вкладку, скопируйте и вставьте следующий код VBA в окно модуля;

Шаг 3: Затем нажмите Runдок-обратный знак-6 кнопку, чтобы применить VBA.

Код VBA для удаления всех пустых строк и столбцов из таблиц:

Sub DeleteEmptyTablerowsandcolumns ()
Приложение.ScreenUpdating = False
Dim Tbl As Table, cel As Cell, i As Long, n As Long, fEmpty As Boolean
С ActiveDocument
Для каждого тбл в. Таблицах
n = Таблица.Столбцов.Количество
Для i = n To 1 Шаг -1
fПусто = Истина
Для каждой ячейки в Tbl.Columns (i) .Cells
Если Len (cel.Range.Text)> 2, то
fEmpty = Ложь
Выход для
End If
Следующий чел
Если fEmpty = True, то Tbl.Columns (i) .Delete
Затем я
Следующая таблица
Конец с
С ActiveDocument
Для каждого тбл в. Таблицах
n = Tbl.Rows.Count
Для i = n To 1 Шаг -1
fПусто = Истина
Для каждой ячейки In Tbl.Rows (i) .Cells
Если Len (cel.Range.Text)> 2, то
fEmpty = Ложь
Выход для
End If
Следующий чел
Если fEmpty = True, то Tbl.Rows (i) .Delete
Затем я
Следующая таблица
Конец с
Set cel = Nothing: Set Tbl = Nothing.
Application.ScreenUpdating = True
End Sub


Удалите все пустые строки и столбцы из таблиц одним щелчком мыши

Kutools for Word предоставляет вам наиболее удобный способ удалить все пустые строки и столбцы из таблиц в документе. Вам просто нужно нажать один раз, и Kutools for Wordс Delete Rows/Columns Утилита быстро удалит все пустые строки и столбцы из всех или выбранных таблиц.

После установки Kutools for Word, пожалуйста, сделайте следующее:(Бесплатная загрузка Kutools for Word Сейчас!)

1. Нажмите Кутулс Плюс > Delete Rows/Columns на Table панель.

doc удалить пустые столбцы строк из таблицы 1

2. Затем появится диалоговое окно, выберите область, из которой вы хотите удалить таблицы, в разделе Искать в, затем отметьте Строка вариант и Пустая строка вариант или чек Колонка вариант и Пустая строка вариант как вам нужно. Если вы хотите удалить все пустые строки и столбцы, вам нужно применить эту операцию дважды.

Появится диалоговое окно, напоминающее вам, сколько таблиц было обработано, щелкните OK чтобы закрыть, а пустые строки и столбцы были удалены из таблиц.
doc kutools удалить пустые строки 4

Наконечник.Если вы хотите удалить пустые строки с листа Excel, Удалить пустые строки полезности Kutools for Excel могу помочь тебе.


Рекомендуемые инструменты для повышения производительности Word

выстрел kutools word kutools tab 1180x121

выстрел kutools word kutools plus tab 1180x120

Kutools For Word — Более 100 расширенных функций для Word, сэкономьте 50% времени

  • Сложные и повторяющиеся операции можно производить разово за секунды.
  • Вставляйте сразу несколько изображений из папок в документ Word.
  • Объединяйте и объединяйте несколько файлов Word из папок в одну в желаемом порядке.
  • Разделите текущий документ на отдельные документы в соответствии с заголовком, разрывом раздела или другими критериями.
  • Преобразование файлов между Doc и Docx, Docx и PDF, набор инструментов для общих преобразований и выбора и т. Д.

The scenario is a table is received each week in Word 2010 that needs adjustments. Among other additions to the macro, the column named «WebSite» needs to be deleted. The column called «WebSite» might not always be in the same position though.

I need to know the VBA code for finding, selecting and deleting a specific table column that can potentially change positions, but will always keep the same column title.

Is there a way to insert a search word in the vba code that will ensure the right column is deleted even if its position in the table can change each time a table is opened in Word?

Martijn Pieters's user avatar

asked Jan 5, 2013 at 19:27

user1951654's user avatar

1

Try:

Dim tbl As Table
Dim cl As Cell

''All tables
For Each tbl In ActiveDocument.Tables
    ''Look in row 1 only ...
    For Each cl In tbl.Rows(1).Cells
        ''For a cell containing website and end of cell
        If cl.Range.Text = "website" & Chr(13) & Chr(7) Then
            ''Select ...
            cl.Column.Select
            ''Allow the user to choose delete
            If MsgBox("Del selected?", vbYesNo) = vbYes Then
                cl.Column.Delete
            End If
        End If
    Next
Next

answered Jan 5, 2013 at 20:56

Fionnuala's user avatar

FionnualaFionnuala

90.1k7 gold badges110 silver badges148 bronze badges

1

It appears you’re trying to delete both the row and the column when a cell has ‘Deleted’ in it. Obviously, if you use one loop to delete a row that has ‘Deleted’ in it, then a second loop to delete a column that has ‘Deleted’ in it, the second loop won’t find anything. Try something based on:

Dim t As Long, r As Long, c As Long, ArrCols() As String
With myDoc
  For t = 21 To 7 Step -1
    With .Tables(t)
      If InStr(1, .Range.Text, "Deleted", 1) Then
        ReDim ArrCols(.Columns.Count)
        For r = .Rows.Count To 1 Step -1
          With .Rows(r)
            If InStr(1, .Range.Text, "Deleted", 1) Then
              For c = 1 To .Cells.Count
                If InStr(1, .Cells(c).Range.Text, "Deleted", 1) Then
                  ArrCols(c) = c
                End If
              Next
              .Delete
            End If
          End With
        Next r
        For c = UBound(ArrCols) To 1 Step -1
          If ArrCols(c) <> "" Then .Columns(c).Delete
        Next
      End If
    End With
  Next
End With

Note how all the loops involving deletions run backwards.

The fact your own code didn’t throw errors with the row deletions was just a coincidence.

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