Use word macro to change three column tables only

The following is an excerpt from a macro I am currently using to reformat large documents in word to our company branding.

    Selection.Tables(1).Select
    Selection.Columns(1).Width = CentimetersToPoints(5.46)
    Selection.Columns(2).Width = CentimetersToPoints(10.92)
    Selection.Rows.HeightRule = wdRowHeightAtLeast
    Selection.Rows.Height = CentimetersToPoints(0.8)

The documents that I get have now been coming through with three column tables as well as two column tables and I would like these to have all columns 5.46 wide, whereas I need the two column tables to stick with the widths I have specified above to keep all the formatting looking good.

I wanted to put in an "if, then" type statement that says if the table has three columns do this, if the table has two then do this but I don't know how to identify 3 column tables from 2 column tables.

preguntado el 24 de agosto de 12 a las 01:08

1 Respuestas

EDIT: updated to deal with rows having uneven column widths.

Dim tbl As Table
Dim rw As Row

Set tbl = ActiveDocument.Tables(1)

For Each rw In tbl.Rows
With rw

    .Cells(1).Width = CentimetersToPoints(5.46)

    If .Cells.Count = 2 Then
        .Cells(2).Width = CentimetersToPoints(10.92)
    ElseIf .Cells.Count = 3 Then
        .Cells(2).Width = CentimetersToPoints(5.46)
        .Cells(3).Width = CentimetersToPoints(5.46)
    Else
        'what do do if not 2 or 3?
    End If

    .HeightRule = wdRowHeightAtLeast
    .Height = CentimetersToPoints(0.8)
End With
Next rw

Respondido 24 ago 12, 06:08

So frustrating - this answer is exactly what I need but when I run it, it says Cannot access individual columns in this collection because the table has mixed cell widths :( - buenamanda

I think that's telling you that your tables have different column widths on different rows, so you might have to loop through the rows and set the column widths cell-by-cell. Not a big Word VBA user, so I'm afraid that's close to my limit of knowledge.... - tim williams

@nicemanda: This solution would work only if you have tables those are homogeneous with all respect, either by rows or by columns. Probably some cells within the table is merged, causing the error to display. - Cilian

See update - should handle uneven cell widths and even merged cells, but you might need to tailor it to fit your exact layout(s)... - tim williams

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.