Word VBA Cells empty test

A

Adam.Effinger

Ok, so I really don't know much, but I'm trying. I have a question.
Anyone can answer.

I am working in VBA Word and can't figure out how to tell if there i
an empty cell in a table. I think that in excel it's selection.text
"" but in Word it has to be something else. Anyone have a clue
 
J

Jay Freedman

Ok, so I really don't know much, but I'm trying. I have a question.
Anyone can answer.

I am working in VBA Word and can't figure out how to tell if there is
an empty cell in a table. I think that in excel it's selection.text =
"" but in Word it has to be something else. Anyone have a clue?

In Word, an "empty" cell contains a cell marker -- if you click the ¶ button to
display nonprinting characters, it looks like a small circle with four diagonal
lines at the corners. In VBA, it's actually two characters, Chr(13) & Chr(7).

So you can write this:

Dim cel As Cell
For Each cel In ActiveDocument.Tables(1).Range.Cells
If Len(cel.Range.Text) < 3 Then
MsgBox "Cell(" & cel.Row.Index & "," _
& cel.Column.Index & ") is empty."
End If
Next

There's an oddity here: If you assign a Range object to the cell's range, and
then move the end of the Range object to the left by _one_ character (not two),
it will exclude the cell marker and give you only the cell's text (if any) or an
empty string. So an alternative to the code above is this:

Dim cel As Cell
Dim rg As Range
For Each cel In ActiveDocument.Tables(1).Range.Cells
Set rg = cel.Range
rg.MoveEnd wdCharacter, -1
If rg.Text = "" Then
MsgBox "Cell(" & cel.Row.Index & "," _
& cel.Column.Index & ") is empty."
End If
Next
 
P

Pesach Shelnitz

Hi,

I'd like to say something about the "oddity" that Jay mentioned. When
nonprintable characters, like the cell-end marker, are included in a Range,
there is a difference between the number of characters returned by the Len
function for the string contained in the Range.Text property and the length
of the Range determined from its Start and End properties or from the number
of characters in its Characters collection.

As Jay pointed out, the cell-end marker consists of two characters, which
are both included in the string obtained from the Range.Text property, but
the Characters collection of the same Range contains only one character for
the cell-end marker.

Thus, the following simpler modification of Jay's code will tell you which
cells are empty.

Dim cel As Cell

For Each cel In ActiveDocument.Tables(1).Range.Cells
If cel.Range.Characters.Count = 1 Then
MsgBox "Cell(" & cel.Row.Index & "," _
& cel.Column.Index & ") is empty."
End If
Next
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top