Home > Software engineering >  How to use VBA to format table column font in Word?
How to use VBA to format table column font in Word?

Time:06-07

I use this code:

Sub d_FormatTableEndNoteDemo2()
Application.ScreenUpdating = False
Dim Tbl As Table
For Each Tbl In ActiveDocument.StoryRanges(wdEndnotesStory).Tables
  With Tbl
    .AllowAutoFit = False
    .Rows.Alignment = wdAlignRowCenter
    .Rows.Height = CentimetersToPoints(0.6)
    
    .Range.Cells.VerticalAlignment = wdCellAlignVerticalTop
    .Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
      
    .Columns(1).Width = CentimetersToPoints(1#)
    .Columns(2).Width = CentimetersToPoints(5#)
    .Columns(3).Width = CentimetersToPoints(11#)
    
  End With
Next
Application.ScreenUpdating = True
End Sub

But I don't know how to fortmat the font of the third column = hidden. Please help me.

CodePudding user response:

Other than Excel you can't access a columns range in Word. In this case you need to iterate over all cells of the specific column:

Public Sub hideTextInColumn(tbl As Table, columnIndex As Long)
    Dim c As Cell
    For Each c In tbl.Columns(columnIndex).Cells
        c.Range.Font.Hidden = True
    Next
End Sub

You would call this sub hideTextInColumn tbl, 3

Within your routine:

Sub d_FormatTableEndNoteDemo2()
Application.ScreenUpdating = False
Dim Tbl As Table
For Each Tbl In ActiveDocument.StoryRanges(wdEndnotesStory).Tables
  With Tbl
    .AllowAutoFit = False
    .Rows.Alignment = wdAlignRowCenter
    .Rows.Height = CentimetersToPoints(0.6)
    
    .Range.Cells.VerticalAlignment = wdCellAlignVerticalTop
    .Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
      
    .Columns(1).Width = CentimetersToPoints(1#)
    .Columns(2).Width = CentimetersToPoints(5#)
    .Columns(3).Width = CentimetersToPoints(11#)

    '---- new
    hideTextInColumn tbl, 3
    '----
    
  End With
Next
Application.ScreenUpdating = True
End Sub

``

CodePudding user response:

The following sub formats cells in column 3 of a table:

Sub FormatTableColumn()
    Dim tbl As Word.Table
    Set tbl = ActiveDocument.Tables(1)
    tbl.Columns(3).Select
    With Selection.Font
        .Name = "Times New Roman"
        .Size = 10
        .Hidden = True
    End With
End Sub
  • Related