2013-08-19 56 views
0

我正在使用VBA宏在Word文檔中插入行(兩列)。問題是插入的行不填充整個頁面,所有的列不具有相同的寬度:展開Word表格VBA

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 
+0

您可以通過直接影響此屬性來設置列的寬度(.Columns(x).Width)。另一方面,我沒有太清楚你的代碼的各個部分;例如:你爲什麼一遍又一遍地分裂,而不是創建你希望的列數(一個,實際上,分割成一個特定的行)? – varocarbas

+0

我對VBA與Word相當陌生。我不確定分裂是做這件事的最好方法。我打開任何代碼提案。如果你有一個,我會很高興看到它。隨意回答併發布一些代碼;)有關信息,我將行添加到單詞模板,並且該模板已經包含一個表(一行(標題),但只有一列)。所有其他行必須有兩列。 – Maxbester

+0

有道理:)我已經用必要的代碼編寫了一個答案來解決您的調整大小問題;從你的代碼中刪除所有的分割setWidths,並把它寫在最上面。 – varocarbas

回答

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;例如:在第三行中,您希望有三列,其中兩列適合主要的第二列。

+0

我仍然有問題...我更新了我的問題。謝謝! – Maxbester

+0

@Maxbester我告訴過你:刪除涉及分割和設置寬度的所有代碼。正如你所看到的,我的代碼輸出兩個相同的列,如果你稍後不修改它,它將保持不變。在你的新代碼中,你仍然有「wrdApp.Selection.Cells.SetWidth 54,RulerStyle:= wdAdjustFirstColumn」 – varocarbas

+0

哦,對不起。我忘了這一行。它現在完美。謝謝!! – Maxbester