Vba word delete rows

i’m trying to delete around 5k table entries in a word table with 2 columns.

The problem is, when I’m using

Function ClearTable(tbl As table)
Dim i As Integer

For i = tbl.Rows.Count To 2 Step -1
    tbl.Rows(i).Delete
Next i
    
End Function

it takes forever. I tried to just select the range from the cells (2,1) to (tbl.rows.count,2) and then use the .delete function, but that only empties the entries and does not remove the entire rows.

This issue seems kinda easy to handle, but I can’t figure it out currently.

Thanks in advance for any hints.

Update:

Function ClearTable(tbl As table)
Dim myCells As Range
Set myCells = ActiveDocument.Range(Start:=tbl.Cell(2, 1).Range.Start, _
            End:=tbl.Cell(tbl.Rows.Count, 2).Range.End)

myCells.Select
Selection.Rows.Delete

End Function

does what I wanted. Thanks to Timothy.

  1. Delete a Row in VBA
  2. How to Delete an Entire Row in VBA
  3. How to Delete Multiple Rows in VBA
  4. How to Delete Alternative Rows in VBA
  5. How to Delete Blank Rows in VBA
  6. How to Delete Rows With Specific Values in VBA
  7. How to Delete Duplicate Rows in VBA

Delete a Row in VBA

We will introduce how we can delete rows for different situations with examples in VBA.

Delete a Row in VBA

Deleting a row from an Excel sheet is an easy job that can be done using the keyboard shortcut method or a mouse or touchpad. But when we are specific about deleting a row or many rows, the VBA route is helpful to work with.

VBA is used to delete row(s) or column(s) of an Excel sheet if unnecessary fields are a part of the data. It can help the user to delete a column on a certain condition.

For example, duplicate rows can be deleted easily using the VBA command.

This article covers some of the main examples and related VBA codes that can be helpful for the user to work on Excel worksheets. These multiple scenarios include:

  1. To delete an Entire Row

    1.1. To delete First Row

    1.2. To delete Specific Row

  2. To delete Multiple Rows

  3. To delete Alternative Rows

  4. To delete Blank Rows

  5. To delete Rows with Specific Date Values

  6. To delete Duplicate Rows

How to Delete an Entire Row in VBA

Now, let’s discuss our first scenario in which we will try to delete the first row in VBA; if we want to delete the first row, VBA’s EntireRow.Delete method can help us.

Now let’s use this method in our example to delete the first row of our Excel sheet.

We will create a sub as deleteFirstRow(). The code for this purpose is shown below.

# VBA
Sub DeleteFirstRow()
ThisWorkbook.Worksheets(1).Rows(1).EntireRow.Delete
End Sub

Output:

deleting first row using the VBA code

The above example shows that this code works by specifying the row refers to a specific number and then uses the EntireRow.Delete method; hence the code can be used for any row by mentioning the row number.

So let’s try to delete row numbers 7 and 10 using the above method as shown below.

# VBA
Sub DeleteSpecificRow()
ThisWorkbook.Worksheets(1).Rows(7).EntireRow.Delete
ThisWorkbook.Worksheets(1).Rows(10).EntireRow.Delete
End Sub

Output:

deleting specific rows using the VBA code

The above example shows that when we pass the row number we want to delete, we can easily delete the entire row using the EntireRow.Delete method.

How to Delete Multiple Rows in VBA

We deleted multiple rows using the multiple EntireRow.Delete methods in the previous example. But now, we will talk about how we can delete multiple rows with just one method.

We can use the range object in VBA to delete multiple rows. The user selects the number of cells meant to be deleted from the Excel sheet first and passes the range as shown below.

# VBA
Sub deleteMultipleRow()
Range("A1:C7").EntireRow.Delete
End Sub

Output:

deleting multiple rows using the VBA code

The above example shows that using the Range() method, we can pass in the range of rows and columns that we want to delete using the EntireRow.Delete method.

Multiple rows and columns can directly get removed from the data. We use the VBA code to remove multiple rows (row 2 to row 7) from the data.

# VBA
Rows("2:7").Delete

Output:

deleting multiple rows using the row function in VBA code

If we want to delete a range of columns (from B to C), we can use the following method.

# VBA
Columns("B:C").Delete

Output:

deleting multiple columns using the columns function in VBA code

How to Delete Alternative Rows in VBA

Excel sheets are used for many purposes, and it is a common software that is used to save records in the form of Excel sheets. Excel sheets are a basic part of the financial system because most of the data is stored in Excel sheets to find the outcome of that data with formulas.

Some financial Excel sheets contain empty rows on alternative numbers that should be removed to improve the record. VBA helps the user to remove entire alternative rows that are not useful.

As shown below, let’s try to remove the rows with alternative numbers and create a sub for this purpose.

Sub AlternateRowDel()
rowLen = Selection.Rows.Count
For a = rowLen To 1 Step -2
    Selection.Rows(a).EntireRow.Delete
Next a
End Sub

Output:

deleting alternative rows in VBA code

As you can see from the above AlternateRowDel() sub, we saved the number of rows from the selection to a variable rowLen which is the total number of rows to be removed entirely.

Inside our sub, we have a for loop that runs with a Step -2, which indicates that every second row will be removed. If we want to remove every third row, then write step -3, and we can use the same process for any different number of the alternative row that the user wants to remove from the data.

How to Delete Blank Rows in VBA

When we are working with a large collection of data, there are chances that many or few rows can be empty. We may want to delete them using VBA because it can be time-consuming and hard to find all of them if we start deleting them manually.

Code usually works more accurately than humans when we provide a large data collection. A method, SpecialCells, can delete these rows.

We can pass the xlCellTypeBlanks, selecting only blank cells. As shown below, let’s go through an example and try to delete all the blank rows using VBA.

# VBA
Sub RemoveBlankRows()
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub

Output:

deleting blank rows in VBA code

The above example shows that we can delete hundreds or thousands of empty rows with one line of code. If we start deleting them manually, it can take hours or days.

How to Delete Rows With Specific Values in VBA

Sometimes we may come across a situation when we have to delete rows that contain a specific value. And it can be a hard and hectic process to delete these rows manually.

But VBA provides the solution for this problem as well. We can create a custom sub that can iterate through all rows and find that specific value.

If the value is found in any of these rows, we can delete that row using the EntireRow.Delete method.

Let’s use this logic in our example, as shown below.

# VBA
Sub RemoveWithValue()
For a = Selection.Rows.Count To 1 Step -1
If Cells(a, 1).Value = "Delete" Then
Cells(a, 1).EntireRow.Delete
End If
Next a
End Sub

Output:

deleting rows with specific value in VBA code

The above example shows that this code will iterate through all rows and find the word delete. If delete was found in any of these rows.

Our code will delete these rows.

How to Delete Duplicate Rows in VBA

There can be situations where we may have a set of data with many duplicates that can cause problems in some of the results. Delete duplicates can also be hectic if we start doing it manually.

It can also be difficult to remember if a certain entry appeared before.

To make it easier and simpler, we can use another method in VBA, RemoveDuplicates. This method takes in a range, finds duplicates, and deletes it.

Let’s use this scenario in our example, as shown below.

# VBA
Range("A1:A10").RemoveDuplicates Columns:=1

Output:

deleting rows with duplicate value in VBA code

The above example shows that we passed the range from the a1 cell to the b10 cell. And our code will find any duplicates and delete them.

How to Use VBA Code in an Excel Sheet

Sometimes people get confused about where they can write a VBA code to run the scripts on their Excel sheets.

Here are a few steps that we can follow to run any of our VBA codes in any Excel sheet we want.

  1. First, we need to open the VBA editor. We can easily open the VBA editor by pressing the following buttons.

    First, we will hold the ALT key, and then we will press the F11 key.

  2. Once the VBA editor is opened, we will go to the View option and select Project Explorer. We can also get the Project Explorer on the left side of the worksheet when we are entered into the VBA editor mode.

  3. Now, we will right-click on the object we want to run the code.

  4. Now, we will add a module to our worksheet. We can easily add the module to our worksheet by clicking on the Insert and selecting Module.

  5. We will copy the code we want to paste and paste it. Or, if we want to write the code there, we can do that.

  6. We will run the code by keeping the cursor and pressing the F5 key. We can also run the VBA code by clicking on the green triangle present in the VBA toolbar.

Please Note:
This article is written for users of the following Microsoft Word versions: 97, 2000, 2002, and 2003. If you are using a later version (Word 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Word, click here: Finding and Deleting Rows.

Written by Allen Wyatt (last updated March 5, 2022)
This tip applies to Word 97, 2000, 2002, and 2003


Sam has a document that contains some tables in which he wants to delete some rows. The rows contain specific text, which he can certainly delete by using Find and Replace, but he wants to delete the entire rows that contain that text.

There is no way to do this (delete rows) using the normal Find and Replace features of Word. Instead, you need to use a macro that will find the text and then delete the entire row. Here is a relatively simple macro that will do the job:

Sub DeleteRowWithSpecifiedText()
    Dim sText As String

    sText = InputBox("Enter text for Row to be deleted")
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = sText
        .Wrap = wdFindContinue
    End With
    Do While Selection.Find.Execute
        If Selection.Information(wdWithInTable) Then
            Selection.Rows.Delete
        End If
    Loop
End Sub

This macro first displays an input box that asks the user to specify the text to be searched for. It then starts searching for all instances of that text. If an instance is found, then the selection is checked to make sure it is within a table. If it is, then the entire row is deleted and the macro moves on to the next occurrence.

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I’ve prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

WordTips is your source for cost-effective Microsoft Word training.
(Microsoft Word is the most popular word processing software in the world.)
This tip (3838) applies to Microsoft Word 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Word (Word 2007 and later) here: Finding and Deleting Rows.

Author Bio

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. Learn more about Allen…

MORE FROM ALLEN

Looking Backward through a Data Table

Sometimes you need to look backward, through the information above your formula, to find the data you need. This can be …

Discover More

Changing the Program that Opens a File

If you have multiple versions of the same program on your system, Windows can become confused as to which version it …

Discover More

Full Path to Workbook

Need to get the full path of your current workbook into the Clipboard? Excel doesn’t make it quite as easy as it used to …

Discover More

More WordTips (menu)

Finding the Previous Occurrence

Using Word’s Object Browser, it is very easy to move among different instances of what you want to search in your …

Discover More

Finding Text Not Using a Particular Font

Word makes it easy to find text that uses a particular font or font characteristics. What it doesn’t do is make it easy …

Discover More

Preserving Bookmarks During Replace Operations

When you do a search and replace operation in Word, it is possible that you could inadvertently wipe out a bookmark or …

Discover More

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

[свернуть]

Like this post? Please share to your friends:
  • Vba word content что это
  • Vba word combobox заполнение
  • Vba word columns width
  • Vba word change the
  • Vba word cell text