sethwalt
sethwalt

Reputation: 41

in Word, delete table rows that don't contain certain text or copy those rows to new file

I will apologize in advance for my limited knowledge of visual basic, but I'm trying to write a macro that will search through a rather large table for a certain string and then either delete the rows that DON'T contain that string or copy all the rows that DO contain it to a new Word document. Just a way to isolate the rows that do contain that string.

Thanks!

Upvotes: 0

Views: 12416

Answers (2)

sethwalt
sethwalt

Reputation: 41

Found a solution from another forum. Thought I'd post here in case it helps someone else:

With ThisDocument.Tables(1)
    For r = .Rows.Count To 1 Step -1
        fnd = False
        For Each c In .Rows(r).Cells
            If InStr(c.Range.Text, "x") > 0 Then fnd = True
        Next
        If Not fnd Then .Rows(r).Delete
    Next
End With

where "x" is the text to be searched for.

I also required a macro to search for a certain text string and delete that row, and that can be accomplished by removing the "not" from the above script. The script does take a while to run (on a table of about 250 rows), though, so at first I thought Word had locked, in case whoever runs this script notices similar behavior and gets worried. Also, I was searching for a text string that was all-caps, and the script didn't recognize it unless the search string ("x") was also in caps.

Additionally, I've found that this macro doesn't work unless it's copied into the word document where it needs to run. Changing ThisDocument to ActiveDocument allows it to work if it's only in the Normal template.

Anyway, hope that helps someone!

Upvotes: 1

Ahmad
Ahmad

Reputation: 12707

If you already know how to put the cursor in the top cell of the column you are iterating through, then here is the code you would want to put so that the entire row will be deleted if the cell text is blank.

Please make the necessary modification to the code as you see fit for your case

Selection.MoveEnd  'This ensures that you select the content of the cell to read
If InStr(Selection.Text, Chr(7)) Then   'if you select the whole cell it will contain
                                        'character 7 (TAB) so you will also select 
                                        '2 additional invisible characters as well 
    If Trim(Mid(Selection.Text, 1, Len(Selection.Text) - 2)) = "" Then
             Selection.Rows.Delete
    End If
Else
 ' you selected part of the text that does not contain invisible characters 
    If Trim(Mid(Selection.Text, 1, 1)) = "" Then
         Selection.Rows.Delete
    End If
End If

Upvotes: 1

Related Questions