我必须创建从Excel复制到其中的大型数据表的文档。这些表可以是数百行,通常约20列宽。许多列已垂直合并,以增强可读性和组数据集。
我已经能够编写一个完全格式化整个表格的宏,除了我无法弄清楚如何自动阻止垂直合并单元格在多个页面中分解/分割。要手动执行此操作,请选择合并中除最后一行之外的所有行,然后在段落设置中启用“保持下一步”。我认为这很容易做到,但如果表中有任何垂直合并的单元格,则无法访问VBA中的各个行。
有没有人知道如何自动浏览行并为已合并在一起的行组设置“Keep With Next”属性?
答案 0 :(得分:1)
是的,使用Word中的合并单元格(以及Excel中的合并单元格)非常烦人。
但是,这可以通过访问表中的单个单元格来完成。我在下面写了以下Sub Sub例程,它应该对你有用。我假设您至少有一列没有垂直合并的单元格,并且您只有一列控制合并块的长度。虽然添加更多控制列应该很容易。
Sub MergedWithNext() 'FTable As Table)
Dim Tester As String
Dim FTable As Table
Dim i As Integer
Dim imax As Integer
Dim RowStart As Integer
Dim RowEnd As Integer
Dim CNMerged As Integer
Dim CNNotMerged As Integer
Dim CNMax As Integer
CNMerged = 2 'A column number that is vertically merged that you don't want to split pages
CNNotMerged = 1 'A column number that has no vertical mergers
Set FTable = Selection.Tables(1)
With FTable
imax = .Rows.Count
CNMax = .Columns.Count
'Start with no rows kept with next
ActiveDocument.Range(Start:=.Cell(1, 1).Range.Start, _
End:=.Cell(imax, CNMax).Range.End).ParagraphFormat.KeepWithNext = False
On Error Resume Next
For i = 2 To imax 'Assume table has header
Tester = .Cell(i, CNMerged).Range.Text 'Test to see if cell exists
If Err.Number = 0 Then 'Only the first row in the merged cell will exist, others will not
'If you are back in this If statement, then you have left the previous block of rows
'even if that was a block of one. The next If statement checks to see if the previous
'row block had more than one row. If so it applies the "KeepWithNext" property
If (RowEnd = (i - 1)) Then
'.Cell(RowStart, 1).Range.ParagraphFormat.KeepWithNext = True
ActiveDocument.Range(Start:=.Cell(RowStart, CNNotMerged).Range.Start, _
End:=.Cell(RowEnd - 1, CNNotMerged).Range.End).ParagraphFormat.KeepWithNext = True
'Use RowEnd - 1 because you don't care if the whole merged block stays with the next
'row that is not part of the merger block
End If
RowStart = i 'Beginning of a possible merger block
RowEnd = 0 'Reset to 0, not really needed, used for clarity
Else
RowEnd = i 'This variable will be used to determine the last merged row
Err.Clear
End If
If i = imax Then 'Last Row
If (RowStart <> imax) Then
ActiveDocument.Range(Start:=.Cell(RowStart, CNNotMerged).Range.Start, _
End:=.Cell(imax - 1, CNNotMerged).Range.End).ParagraphFormat.KeepWithNext = True
'Use imax - 1 because you don't care if the whole merged block stays with the next
'row that is not part of the merger block
End If
End If
Next i
On Error GoTo 0
End With
End Sub
此代码将循环遍历表中的每一行,不包括标题,以查找垂直合并的单元格。一旦找到块,它将为块中的每一行分配“Keep With Next”属性,最后一行除外。