遍历所有Word文档,并在文档的每个表格前插入分节符

Sub 遍历所有Word文档并在文档的每个表格前插入分节符()
    
    ' 选择目标文件夹
    Set fileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    With fileDialog
        .Title = "请选择包含Word文档的文件夹"
        .AllowMultiSelect = False
        If .Show <> -1 Then Exit Sub  ' 用户取消选择则退出
        folderPath = .SelectedItems(1) & "\"
    End With
    
    ' 遍历文件夹中的Word文档
    fileName = Dir(folderPath & "*.docx")  ' 仅处理docx格式,如需doc可添加"*.doc"
    Do While fileName <> ""
        ' 打开文档
        Set doc = Documents.Open(FileName:=folderPath & fileName)
        
        ' 检查文档是否有表格
        If doc.Tables.Count > 0 Then
            ' 从后往前遍历表格
            For i = doc.Tables.Count To 1 Step -1
                Set tbl = doc.Tables(i)
                
                ' 定位到表格前的位置
                Set insertRange = tbl.Range.Duplicate
                insertRange.Collapse 1  ' wdCollapseStart(值为1)
                
                ' 仅当表格不在文档开头时插入分节符
                If insertRange.Start > 0 Then
                    ' 插入“下一页”分节符(可根据需求修改类型)
                    insertRange.InsertBreak Type:=wdSectionBreakNextPage
                End If
            Next
            
            ' 保存并关闭文档
            doc.Save
            doc.Close SaveChanges:=wdSaveChanges            
        Else
            doc.Close SaveChanges:=wdDoNotSaveChanges            
        End If
        
        ' 继续下一个文档
        fileName = Dir
    Loop
    
    MsgBox "所有Word文档处理完成!", vbInformation
End Sub
posted @ 2025-11-27 10:34  python_learn  阅读(1)  评论(0)    收藏  举报