View Single Post
 
Old 04-04-2018, 10:17 AM
Cosmo Cosmo is offline Windows Vista Office 2007
Competent Performer
 
Join Date: Mar 2012
Posts: 240
Cosmo is on a distinguished road
Default

Quote:
Originally Posted by slaycock View Post
'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...
Thanks, I see what you are saying now about using the range (didn't quite pick up your meaning in your original post).

It feels a little more of a round-about way to do it (reading the code months later might not be as easily identifiable as to what is going on as a 'TableExists' function)
Reply With Quote