WD97: Table Macro Returns Incorrect Result on Empty Cell (188775)
The information in this article applies to:
- Microsoft Word 97 for Windows
This article was previously published under Q188775 SYMPTOMS
When you run a Visual Basic for Applications macro to select a table cell
and then test the contents of the cell or check whether the cell is empty,
it may return a false or invalid result.
CAUSE
This behavior is by design of Microsoft Word. In Microsoft Word for
Windows, there are markers in every cell of the table that store formatting
attributes. When you select a cell in a table manually by double-clicking
it or programmatically with Select method, the cell marker is included in
the selection.
WORKAROUND
When you write macros to test the content of a cell in Word, you must
remove or account for two additional characters at the right side or end of
the selection. These characters represent the cell marker.
If you are testing to see if a table cell is empty, then use one of the
following examples.
Method One--Check for a Character other Than Cell Marker
This macro inserts a space at the end of the cell, and then moves the
insertion point to the beginning of the cell. If MyVar returns a space, the
cell is empty. This macro does not work with leading spaces in the text.
Sub TableCellSpace()
ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Select
Selection.InsertAfter " "
Selection.MoveLeft Unit:=wdCharacter, Count:=1
MyVar = Selection.Text
If MyVar= " " then MsgBox "Empty Cell"
End Sub
Method Two--Check All Cells in Table Suppress Leading Spaces
This macro checks the number of characters in a table cell, using the Len
function to count the number of characters and LTrim function to suppress
leading spaces in the selected content.
To compensate for the cell marker, subtract 2 from the result of the LTrim
and Len function. All of these features are combined together to apply to
the content of the selection.
Sub TableCellTest()
For varRow = 1 To ActiveDocument.Tables(1).Rows.Count
For varCol = 1 To ActiveDocument.Tables(1).Columns.Count
ActiveDocument.Tables(1).Cell(varRow, varCol).Range.Select
'Gets number of characters in cell minus cell marker and
'leading spaces, then assigns it to the variable.
MyVar = Len(LTrim(Selection.Range.Text)) - 2
If MyVar = 0 Then
MsgBox "Cell row " & r & ", col. " & c & " is empty"
End If
Next varCol
Next varRow
Selection.MoveDown unit:=wdLine
End Sub
REFERENCES
For additional information, please see the following article in the
Microsoft Knowledge Base:
173707 OFF97: How to Run Sample Code from Knowledge Base Articles
Modification Type: | Major | Last Reviewed: | 6/17/2005 |
---|
Keywords: | kbprb KB188775 |
---|
|