使用样式格式化文件中的所有表

时间:2013-04-09 10:44:20

标签: vba ms-word word-vba

我目前正在使用某种文档,其中包含大量的表格。正如你现在可能已经猜到的那样,我需要用某种风格来格式化它们。 因此,有一个专门为此目的而制作的VBA宏 - 它创建所需的样式,然后将其应用于文件中的所有表。但是现在,当我处理大型文档时,这似乎是一个问题。 所以,让我们看看工作代码,省略部分,创建样式的地方:

Dim oTable As Table
For Each oTable In ActiveDocument.Tables
oTable.Select
Selection.Tables(1).ApplyStyleDirectFormatting ("FooStyle")
Selection.Tables(1).AutoFitBehavior (wdAutoFitFixed)
Selection.Tables(1).ApplyStyleRowBands = True
With Selection.Tables(1).Borders
    .InsideLineStyle = wdLineStyleSingle
    .InsideLineWidth = wdLineWidth025pt
    .OutsideLineStyle = wdLineStyleSingle
    .OutsideLineWidth = wdLineWidth025pt
End With

'Make a list for last row of the table
Selection.Tables(1).Cell(Row:=8, Column:=1).Range.Select
Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=ListGalleries(wdOutlineNumberGallery).ListTemplates(2)
Next

因此,此代码适用于少于600页的文档。否则它会在

行停止
.InsideLineStyle = wdLineStyleSingle

运行时错误4605讲述有关内存和磁盘空间的故事。我做了一些研究,发现this awesome thread讲述了选择的缺点。然后按照给定的建议并稍微更改宏代码,结果如下:

Dim lTbl As Long
For lTbl = 1 To ActiveDocument.Tables.Count
ActiveDocument.Tables(lTbl).ApplyStyleDirectFormatting ("BarStyle")
ActiveDocument.Tables(lTbl).AutoFitBehavior (wdAutoFitFixed)
ActiveDocument.Tables(lTbl).ApplyStyleRowBands = True
With ActiveDocument.Tables(lTbl).Borders
    .InsideLineStyle = wdLineStyleSingle
    .InsideLineWidth = wdLineWidth025pt
    .OutsideLineStyle = wdLineStyleSingle
    .OutsideLineWidth = wdLineWidth025pt
End With

'Make a list for last row of the table
ActiveDocument.Tables(lTbl).Cell(Row:=8, Column:=1).Range.ListFormat.ApplyListTemplate ListTemplate:=ListGalleries(wdOutlineNumberGallery).ListTemplates(2)
Next

是的,毛骨悚然的长线。不,没有改变。似乎没有更多的选择,但在同一个地方仍然是相同的错误。所以我尝试在出现错误时更改调试器停止的部分:

For Each oCell In ActiveDocument.Tables(lTbl).Range.Cells
    oCell.Borders.OutsideLineStyle = wdLineStyleSingle
    oCell.Borders.OutsideLineWidth = wdLineWidth025pt
    Next

无济于事 - 仍然遇到同样的问题。在这一点上,我决定做一些实验并在代码的最后一行旁边删除(那个长长的**线)...而且瞧 - 宏的工作就像一个魅力,没有错误,没有抱怨,没有。为了论证,我尝试对此宏的第一个版本进行相同的更改,结果是相同的 - 似乎一直是该行的错误。 因此,保留它不是一个解决方案,因为最后一行中的编号列表是必须的。那么,我应该怎么做这个宏,它不会弹出这个错误?

1 个答案:

答案 0 :(得分:1)

通过将任务分成两个循环可以解决这种问题。第一次迭代将更改表格式。第二次迭代会将ListFormat添加到预期的位置。

当然,结果我们得到了更慢的子程序,但最后我们得到了我们需要的东西。