idk123
idk123

Reputation: 29

Removing a row in a table if it doesn't contain keyword

Right now I have a really long table in a Word doc which I populated from an Excel worksheet. It has 6 columns and I'm trying to code something in Word VBA that will go through all the rows in the table and delete the entire row if the cell in the first column DOES NOT start with an equal sign ("=").

For example, I'm only trying to keep the rows that has texts like,

 "=1+S -03F7", "=1+M -06M1", etc. etc.

How would I code this? I can't give the code anything specific to look for since the parts after the equal sign will be different for every row.

So this wouldn't work, right?:

If Not ActiveDocument.Tables(83).Columns(1).Range.Text = "=" Then
EntireRow.Select
Selection.Delete

I guess I should reference to cells in column 1, not the column itself... Also, it doesn't work because it's only looking for things with just the equal sign... And I don't know how I can get it to select the row if it find the cell without the equal sign. I don't know how to match by case in the cell of the first column.

Upvotes: 1

Views: 949

Answers (1)

Jane
Jane

Reputation: 851

You can loop through the rows in the table using the Rows property. You can then find the first cell in that Row using the Cells property. You can then check just the first character of the Range:

Sub DeleteUnwantedRows()
    Dim t As Table
    Dim r As Row
    Set t = ActiveDocument.Tables(1)

    For Each r In t.Rows
        If r.Cells(1).Range.Characters(1) <> "=" Then r.Delete
    Next r
End Sub

Upvotes: 2

Related Questions