Is there a way I could go through each table cell in a document,
removing the last character from each cell? I know that each table
cell ends with a table end cell marker, so perhaps what I what is to
remove the last-but-one character in each cell.
I guess it isn't as easy as saying:
For Each Cell in ActiveDocument.Tables(1)
NewContent=Left(Content, Len(Content)-2)
Next
... so where am I going wrong? Barking up the wrong tree completely,
or just slightly out?
No, it certainly isn't that easy.
For one thing, there's no way in VBA to say "for each cell in this table."
You could loop through the table's Rows collection and, for each row, loop
through its cells (or loop through each cell in each column). The problem
with that approach is that VBA barfs if you try to access the Rows
collection of a table that has vertically merged cells, or the Columns
collection of a table that has horizontally merged cells. The only
reasonable way to deal with it is to start with the cell in row 1/column 1
and keep doing "process this cell and go to the next cell" until you run out
of cells.
You also have to check for "empty" cells, ones that contain only the cell
marker, because trying to use the Left() method with a negative length would
throw an error.
Try it this way:
Sub ZapLastCharInCell()
Dim myRg As Range
Dim myTbl As Table
Dim myCel As Cell
On Error GoTo ErrHdl
For Each myTbl In ActiveDocument.Tables
' every table has at least one cell
Set myCel = myTbl.Cell(1, 1)
Do
Set myRg = myCel.Range
' exclude the cell marker from the range
myRg.MoveEnd unit:=wdCharacter, Count:=-1
' test that there's something there before shortening
If Len(myRg.Text) > 0 Then
myRg.Text = Left$(myRg.Text, Len(myRg.Text) - 1)
End If
' try to go to the next cell
' (left to right, then down to next row)
Set myCel = myCel.Next
Loop Until myCel Is Nothing
Next
Exit Sub
ErrHdl:
MsgBox Err.Number & vbCr & Err.Description, , "Error"
End Sub
--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.