1.选择所有的表
Sub SelectAllTables()
Dim tempTable As Table
Application.ScreenUpdating = False
'判断文档是否被保护
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
MsgBox "文档已保护,此时不能选中多个表格!"
Exit Sub
End If
'删除所有可编辑的区域
ActiveDocument.DeleteAllEditableRanges wdEditorEveryone
'添加可编辑区域
For Each tempTable In ActiveDocument.Tables
tempTable.Range.Editors.Add wdEditorEveryone
Next
'选中所有可编辑区域
ActiveDocument.SelectAllEditableRanges wdEditorEveryone
'删除所有可编辑的区域
ActiveDocument.DeleteAllEditableRanges wdEditorEveryone
Application.ScreenUpdating = True
End Sub
上面代码用于选择word中所有表当我们运行完上面的宏后,我们所有打开的word中表已被选择,选中后可以改变表的统一所有表的样式
2.所表设置内容自适应
Sub SelectAllTables()
Application.Browser.Target = wdBrowseTable
For i = 1 To ActiveDocument.Tables.Count
ActiveDocument.Tables(i).AutoFitBehavior (wdAutoFitContent) '根据内容自动调整表格
ActiveDocument.Tables(i).AutoFitBehavior (wdAutoFitWindow) '根据窗口自动调整表格
ActiveDocument.Tables(i).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter '水平居中
ActiveDocument.Tables(i).Range.ParagraphFormat.Alignment = wdCellAlignVerticalCenter '垂直居中
Next i
3.末行合并自动分类填充
def word1():
# 打开word文档
word = win32com.client.Dispatch(‘Word.Application’)
path = “D:\work\cs\测试记录.docx”
doc = word.Documents.Open(FileName=path, Encoding=‘gbk’)
for table in doc.Tables:
youxiao=[0,1,2,3,4,5]
youxiao.append(len(table.rows)-1)
youxiao.append(len(table.rows)-2)
istabl=True
for index,row in enumerate( table.Rows):
changdu=len(row.Cells)
if(index in youxiao):
# print(index)
word.Selection.SetRange(table.Cell(index+1,changdu-1).Range.Start, table.Cell(index+1,changdu).Range.End)
word.Selection.Cells.Merge()
else:
if(istabl):
table.Cell(index+1, changdu).Range.Text = "实际执行结果"
istabl=False
else:
table.Cell(index + 1, changdu).Range.Text = "通过"
# table.AutoFitBehavior(wdAutoFitContent)
path = "D:\\work\\cs\\新建 Microsoft Word 文档4.docx"
doc.SaveAs(path)
doc.Close()
word.Quit()
4.统一加列
path=“D:\work\cs\新建 Microsoft Word 文档.docx”
doc =Document(path)
for table in doc.tables:
table.add_column(Cm(20))
doc.save(“D:\work\cs\新建 Microsoft Word 文档1.docx”)