展开Word表格VBA
我正在使用VBA宏在Word文档中插入行(两列)。问题是插入的行不填充整个页面,所有的列不具有相同的宽度:展开Word表格VBA
我的问题是:如何给出相同宽度的所有列和扩大表格以填充页面宽度?
这里是我的功能:
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
可以做,以实现你追求的是在开始建立柱的尺寸,进行任何修改之前的最好的事情。示例代码:
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
;例如:在第三行中,您希望有三列,其中两列适合主要的第二列。
我仍然有问题...我更新了我的问题。谢谢! – Maxbester
@Maxbester我告诉过你:删除涉及分割和设置宽度的所有代码。正如你所看到的,我的代码输出两个相同的列,如果你稍后不修改它,它将保持不变。在你的新代码中,你仍然有“wrdApp.Selection.Cells.SetWidth 54,RulerStyle:= wdAdjustFirstColumn” – varocarbas
哦,对不起。我忘了这一行。它现在完美。谢谢!! – Maxbester
您可以通过直接影响此属性来设置列的宽度(.Columns(x).Width)。另一方面,我没有太清楚你的代码的各个部分;例如:你为什么一遍又一遍地分裂,而不是创建你希望的列数(一个,实际上,分割成一个特定的行)? – varocarbas
我对VBA与Word相当陌生。我不确定分裂是做这件事的最好方法。我打开任何代码提案。如果你有一个,我会很高兴看到它。随意回答并发布一些代码;)有关信息,我将行添加到单词模板,并且该模板已经包含一个表(一行(标题),但只有一列)。所有其他行必须有两列。 – Maxbester
有道理:)我已经用必要的代码编写了一个答案来解决您的调整大小问题;从你的代码中删除所有的分割setWidths,并把它写在最上面。 – varocarbas