View Single Post
 
Old 04-04-2018, 08:32 AM
slaycock slaycock is offline Windows 7 64bit Office 2016
Expert
 
Join Date: Sep 2013
Posts: 256
slaycock is on a distinguished road
Default

'oTbl is nothing' - you are comparing objects not values.

The 'is' operator is not the same as the '=' operator'. The 'is' operator compares the references to objects, not the content of the objects.

Deleting all rows deletes the word object and leaves oTbl in an indeterminate state.
Thus you can refer to the VBA object but trying to access its information gives an error because there is no object. If the object has been deleted then oTbl will be nothing. Hence you will be comparing the reference to nothing with the reference to nothing which is always true. One of the little joys of working with objects.

The simplest way to deal with this situation is by abstracting the object range (in fact ranges are by far the best way to work in VBA for Word). The following code works without needing an on error statement assuming there is at least one uniform table in the active document.


Code:
Sub Macro2()

    Dim oTbl As Word.Table
    Dim oTbl_range As Word.Range
    
    Set oTbl = ActiveDocument.Tables(1)
    Set oTbl_range = oTbl.Range
    Do Until oTbl_range.Tables.Count = 0
    
        Debug.Print oTbl.Range.Rows.Count
        oTbl.Rows(1).Delete
    Loop

End Sub
Applying the same approach to you code gives

Code:
Dim oTbl_range As Word.Range
    Set oTbl_range = oTbl.Range
    ' Remove empty rows
    With oTble_range.Tables(1)
        RowCount = .Rows.Count
        columnCount = .Columns.Count
        For Row = RowCount To 1 Step -1
            Delete = True
            For Column = 1 To columnCount
                If Not (.Cell(Row, Column).Range.Text = Chr(13) & Chr(7)) Then
                    Delete = False
                    Exit For
                End If
            Next Column
            If (Delete) Then
                ' Remove row
                Call .Rows(Row).Delete
            End If
        Next Row
    End With
 
' NOTE: Need to check to see if table still exists here (If all rows were deleted)
If oTbl_range.Tables.Count > 0 Then ' by abstracting the table range you can subsequently test for the presence of a table in the range
    ' Do other processing steps to table...
Reply With Quote