我有一个包含 84 个 Word 文档 (.docx) 的文件夹。每个文档都包含一个布局相同的表格(某些文档跨越 2 页)。但是,列宽并不总是相同。
我想让所有表格列的宽度都相同,均为 2 英寸,这样我就可以将所有文件保存为 PDF,并准备在另一个过程中使用它们,我不会详细说明。
我有一个 Word VBA 宏,它根据用户提示的文件路径对文件夹中的所有 .docx 文件运行脚本(如下)。这部分有效 - 没有问题。
但是,当我的脚本尝试将文档表格中的所有列设置为相同宽度时,这不起作用。在此处显示的示例文档中,它仅适用于前 3 列。
图 2(上图):这是运行宏后表格的样子。在此示例中,我运行宏将所有列宽度设置为 1.5 ( InchesToPoints(1.5))。可以看到只调整了前3列,第4-7列没有修改。
图 3(上图):这就是我在运行宏将所有列宽度设置为 1.5 英寸后所期望的表格外观。
以下是原始文档的链接:https://www.dropbox.com/s/cm0fqr6o7xgavpv/1-Accounting-Standards.docx ?dl=0
我在创建的另一个文件上测试了该宏,其中插入了 3 个表。
图 4(上图):我创建了一个包含 3 个表的新文件,所有表的列宽都不同。
图 5(上图):使用此测试文件在与之前的示例文档相同的文件夹中运行宏,显示该宏有效,并将所有表中的列调整为指定的宽度。
这里发生了什么?为什么没有SetTableWidths按预期工作?
我猜测这可能是因为原始word文档中的原始表格包含合并的单元格,否则为什么脚本无法在第4-7列上运行?
任何帮助将不胜感激。
Sub RunMacroOnAllFilesInFolder()
Dim flpath As String, fl As String
flpath = InputBox("Please enter the path to the folder you want to run the macro on.")
If flpath = "" Then Exit Sub
If Right(flpath, 1) <> Application.PathSeparator Then flpath = flpath & Application.PathSeparator
fl = Dir(flpath & "*.docx")
Application.ScreenUpdating = False
Do Until fl = ""
MyMacro flpath, fl
fl = Dir
Loop
End Sub
Sub MyMacro(flpath As String, fl As String)
Dim doc As Document
Set doc = Documents.Open(flpath & fl)
'Your code below
SetTableWidths doc
DeleteAllHeadersFooters doc
'your code above
doc.Save
doc.Close SaveChanges:=wdSaveChanges
End Sub
Sub SetTableWidths(doc As Document)
Dim t As Table
For Each t In doc.Tables
t.Columns.Width = InchesToPoints(2)
Next t
End Sub
Sub DeleteAllHeadersFooters(doc As Document)
Dim sec As Section
Dim hd_ft As HeaderFooter
For Each sec In ActiveDocument.Sections
For Each hd_ft In sec.Headers
hd_ft.Range.Delete
Next
For Each hd_ft In sec.Footers
hd_ft.Range.Delete
Next
Next sec
End Sub
Run Code Online (Sandbox Code Playgroud)
我没有写VBA宏。我是在这两个地方在线获取的:
这里显示的示例文件是新加坡政府的财产:http ://www.skillsfuture.sg/skills-framework
尝试基于以下内容:
Sub SetTableWidths(Doc As Document)
Dim Tbl As Table, c As Long, sWdth As Single
sWdth = InchesToPoints(14)
For Each Tbl In Doc.Tables
With Tbl
.PreferredWidthType = wdPreferredWidthPoints
.PreferredWidth = sWdth
sWdth = sWdth / 7
With .Range
For c = 1 To 5 Step 2
.Cells(c).Width = sWdth
Next
For c = 2 To 6 Step 2
.Cells(c).Width = sWdth * 6
Next
For c = 7 To .Cells.Count
.Cells(c).Width = sWdth
Next
End With
End With
Next
End Sub
Run Code Online (Sandbox Code Playgroud)