Log in

View Full Version : [SOLVED:] Formatting alternate cells in table



JamesT
09-27-2016, 10:35 PM
Hi,

I'm trying to format cell heights in a table in the third column (where the cells have been split) - every even cell needs to be .5cm and odd cell (excluding the first) needs to be 3.5cm.

The code i'm running with is below and i'm getting a 'requested member of the collection does not exist' error, I'm a newbie at coding....
----Sub formatnewrows()


Dim r As Integer
Dim c As Integer




c = ActiveDocument.Tables(2).Columns(3).Cells.Count
MsgBox c

For r = 2 To c
If r Mod 2 = 0 Then
Selection.Tables(2).Cell(r, 3).Height = CentimetersToPoints(0.5)
Else
Selection.Tables(2).Cell(r, 3).Height = CentimetersToPoints(3.14)
End If

Next r
End Sub

gmayor
09-28-2016, 12:06 AM
Split cells are difficult to deal with using VBA when you know what the table looks like. When you don't it is impossible.

Boris_R
09-28-2016, 03:15 AM
1. Completely agree with gmayor.
2. If you are lucky and your table has a simple structure, the following code would work.





Sub formatnewrows1()


Dim r As Integer
Dim c As Integer

c = ActiveDocument.Tables(2).Columns(3).Cells.Count
MsgBox c
With ActiveDocument.Tables(2)
For r = 2 To c
If r Mod 2 = 0 Then
.Cell(r, 3).SetHeight RowHeight:=CentimetersToPoints(0.5), HeightRule:=wdRowHeightExactly
Else
.Cell(r, 3).SetHeight RowHeight:=CentimetersToPoints(3.14), HeightRule:=wdRowHeightExactly
End If
Next r
End With
End Sub

gmaxey
09-28-2016, 04:40 AM
Boris,

You can't get c (the cell count) that way. Perhaps:


Sub formatnewrows()
Dim r As Integer
Dim c As Integer
Dim oCell As Cell
For Each oCell In ActiveDocument.Tables(2).Range.Cells
If oCell.Range.Information(wdEndOfRangeColumnNumber) = 3 Then
c = c + 1
End If
Next oCell
MsgBox c
With ActiveDocument.Tables(2)
For r = 2 To c
If r Mod 2 = 0 Then
.Cell(r, 3).SetHeight RowHeight:=CentimetersToPoints(0.5), HeightRule:=wdRowHeightExactly
Else
.Cell(r, 3).SetHeight RowHeight:=CentimetersToPoints(3.14), HeightRule:=wdRowHeightExactly
End If
Next r
End With
End Sub

JamesT
10-03-2016, 11:08 PM
Hi Gents,

Apologies for not uploading the table, didn't know how.

Boris - your code worked a treat - Cheers.