展开Word表VBA

时间:2013-08-19 14:10:27

标签: ms-word formatting word-vba

我正在使用VBA宏在word文档中插入行(两列)。问题是插入的行没有填满整个页面,并且所有列都没有相同的宽度:

enter image description here

我的问题是:如何为所有列提供相同的宽度并展开表格以填充页面宽度?

这是我的功能:

Private Function CreateWordDoc(ByVal wrdApp As Word.Application, ByRef Objects() As OwnClass, ByVal sFilename As String, ByVal sPath As String)
    Dim i As Integer
    Dim wrdDoc As Word.Document
    Dim MyObj As OwnClass

    Dim wrdTppTable As Word.Table

    Set wrdDoc = wrdApp.Documents.Add(sFilename, Visible:=True)

    Set wrdTppTable = wrdDoc.Tables(2)

    For i = 0 To UBound(Objects) - 1
        Set MyObj = Objects(i)
        ' Add a row to the table and select it
        wrdTppTable.Rows.Add.Select
        ' Work with the selected row
        With wrdApp.Selection.Range
            ' Make sure the row is on two columns
            .Cells.Split 1, 2, True
            ' Set the text font parameters
            With .Font
                .ColorIndex = wdBlack
                .name = "Arial"
                .size = 11
                .Bold = False
            End With
            ' Write text in the cell
            .Text = MyObj.GetKey & ": " & MyObj.GetValue
            ' Then select the next cell in the row
            .Next.Select
        End With
        ' Work with the second column of the row
        wrdApp.Selection.Cells.SetWidth 54, RulerStyle:=wdAdjustFirstColumn
        With wrdApp.Selection.Range
            With .Font
                .ColorIndex = wdBlack
                .name = "Arial"
                .size = 11
                .Bold = False
            End With
            ' Write the cell
            .Text = MyObj.GetId
        End With
    Next
End Function

1 个答案:

答案 0 :(得分:0)

在完成任何修改之前,您可以做的最好的事情是在开始时设置列的尺寸。示例代码:

Dim availableWidth As Integer
availableWidth = wrdDoc.PageSetup.PageWidth - wrdDoc.PageSetup.LeftMargin - wrdDoc.PageSetup.RightMargin

With wrdTppTable
   .Columns.Add 'Adding the required column
    'Resizing both columns on account of the available space
   .Columns(1).Width = availableWidth / 2
   .Columns(2).Width = availableWidth / 2
   .Cell(1, 1).Merge .Cell(1, 2)
End With

在此代码之后,您可以开始迭代单元格并执行所需的操作,只需添加行即可。仅在真正需要的情况下使用Cells.Split;例如:在第三行中,您希望有三列,其中两列适合主要的第二列。