0
votes

I have a Word document with many tables. I want to delete all tables whose first cell doesn't match the specified text and for that I have to following VBA script.

But the If condition doesn't seem to work; it keeps returning true for all tables, even though the Debug.Print shows different names.

Sub EWT()
    Dim t As Table
    For Each t In ActiveDocument.Tables
        t.Style = "Table Grid"
        
        'If t.Cell(1, 1).Range.Text <> "Field Name" Then
        If Not t.Cell(1, 1).Range.Text = "Field Name" Then
            't.Delete
            Debug.Print t.Cell(1, 1).Range.Text
        End If
    Next
End Sub

A chunk from Debug.Print:

Field Name

PRIMARY KEY NAME

Field Name

PRIMARY KEY NAME

Field Name

Field Name

Field Name

PRIMARY KEY NAME

Field Name

PRIMARY KEY NAME

Field Name

PRIMARY KEY NAME

Field Name

PRIMARY KEY NAME
1

1 Answers

0
votes

That is because all cells end with Chr(13) & Chr(7). (The clue would be the empty lines in the debug window). If you test for "Field Name" & Chr(13) & Chr(7) it should work.

If you don't want to remember the characters you could also test the left part of the string: Left(cellContent, Len(cellContent) - 2) = "Field Name".