分页保存为新文档

' WORD功能。如何将一个多页文档分别每页保存为多个单页文档。以下为代码

Sub 分页保存为新文档()
    '分页保存,适用于WORD97及其以上版本
    Dim objShell As Object, objFolder As Object, strNameLenth As Integer
    Dim mySelection As Selection, myfolder As String, myArray() As String
    Dim ThisDoc As Document, myDoc As Document, strName As String, n As Integer
    Dim myRange As Range, PageString As String, pgOrientation As WdOrientation
    Dim sinLeft As Single, sinRight As Single, sinTop As Single, sinBottom As Single
    Dim ErrChar() As Variant, ochar As Variant, sinStart As Single, sinEnd As Single
    Const myMsgTitle As String = "ExcelHome_ShouRou"
    Dim vbYN As VbMsgBoxResult
    sinStart = Timer
    On Error GoTo errhandle    '设置错误处理
    '创建一个Shell.Application对象
    Set objShell = CreateObject("Shell.Application")
    '取得文件夹浏览器
    Set objFolder = objShell.BrowseForFolder(0, "请选择一个文件夹", 0, 0)
    If objFolder Is Nothing Then Exit Sub
    myfolder = objFolder.Self.Path & "\"
    Set objFolder = Nothing: Set objShell = Nothing
    Set ThisDoc = ActiveDocument    '定义一个Document对象,以利用本程序作为加载宏
    Set mySelection = ThisDoc.ActiveWindow.Selection
    '文件自动命名时必须规避的字符
    ErrChar = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    '一些特列字符
    For n = 0 To 31
        ReDim Preserve ErrChar(UBound(ErrChar) + 1)
        ErrChar(UBound(ErrChar)) = Chr(n)
    Next
    strNameLenth = Val(VBA.InputBox(Prompt:="请输入您需要设置的文件名长度,0或者取消将自动命名!", Title:=myMsgTitle, Default:=10))
    If strNameLenth > 255 Then strNameLenth = 0
    vbYN = MsgBox("是否需要处理页尾的分隔符(分页符/分节符)?它可能会影响文档结构.", vbYesNo + vbInformation + vbDefaultButton2, myMsgTitle)
    Application.ScreenUpdating = False    '关闭屏幕更新
    '在文档的每页中循环
    For n = 1 To mySelection.Information(wdNumberOfPagesInDocument)
        mySelection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Name:=n
        Set myRange = ThisDoc.Bookmarks("\PAGE").Range
        If vbYN = vbYes And VBA.Asc(myRange.Characters.Last.Text) = 12 Then _
           myRange.SetRange myRange.Start, myRange.End - 1
        '取得一个以段落标记为分隔符的一维数组
        myArray = VBA.Split(myRange.Text, Chr(13))
        '将所有文本合并为一个字符串
        PageString = VBA.Join(myArray, "")
        '取得文档中每节的页面设置
        With myRange.Sections(1).PageSetup
            sinLeft = .LeftMargin    '左页边距
            sinRight = .RightMargin    '右页边距
            sinTop = .TopMargin    '上边距
            sinBottom = .BottomMargin    '下边距
            pgOrientation = .Orientation    '纸张方向
        End With
        For Each ochar In ErrChar    '进行一系列替换,即删除无效字符
            PageString = VBA.Replace(PageString, ochar, "")
        Next
        If strNameLenth = 0 Then
            strName = ThisDoc.Name
            strName = VBA.Replace(LCase(strName), ".doc", "")
            strName = strName & "_" & n
        Else
            strName = VBA.Left(PageString, strNameLenth)    '取得文件名
            If strName = "" Then
                strName = ThisDoc.Name
                strName = VBA.Replace(LCase(strName), ".doc", "")
                strName = strName & "_" & n
            End If
        End If
        strName = strName & ".doc"
        myRange.Copy    '复制
        Set myDoc = Documents.Add(Visible:=True)    '新建一个隐藏的空白文档
        With myDoc
            With .Content
                .Paste    '粘贴
                .Paragraphs.Last.Range.Delete    '删除最后一个段落标记
                With .Find
                    .ClearFormatting
                    .Text = "^b"
                    .Replacement.ClearFormatting
                    .Replacement.Text = ""
                    .Execute Replace:=2
                End With
            End With
            With .PageSetup    '进行页面设置
                .Orientation = pgOrientation
                .LeftMargin = sinLeft
                .RightMargin = sinRight
                .TopMargin = sinTop
                .BottomMargin = sinBottom
            End With
            '如果有相同的文档,则自动命名
            If VBA.Dir(myfolder & strName, vbDirectory) <> "" Then strName = "Page_" & n & ".doc"
            .SaveAs myfolder & strName    '另存为
            .Close    '关闭文档
        End With
    Next
    ThisDoc.Characters(1).Copy    '变相清空剪贴板
    Application.ScreenUpdating = True    '恢复屏幕更新
    sinEnd = Timer    '取得代码运行结束的时间
    If MsgBox("分页保存结束,用时:" & sinEnd - sinStart & _
              "秒,是否打开指定文件夹查看分页保存后的文档情况?", vbYesNo, myMsgTitle) = vbYes Then _
       ThisDoc.FollowHyperlink myfolder
    Exit Sub
errhandle:
    MsgBox "错误号:" & Err.Number & vbLf & "出错原因:" & Err.Description, myMsgTitle
    Err.Clear
    Application.ScreenUpdating = True    '恢复屏幕更新
End Sub

 

### 使用Python拆分Word文档 要实现通过 Python 将 Word 文档拆分为多个文件的功能,可以利用 `python-docx` 库来处理 `.docx` 文件。以下是详细的说明以及代码示例。 #### 安装依赖库 为了操作 Word 文档,需安装 `python-docx` 库。可以通过以下命令完成安装: ```bash pip install python-docx ``` #### 拆分逻辑概述 通常情况下,可以根据段落数量、页数或者特定关键字将一个 Word 文档分割成若干部分。每一段落会被保存到一个Word 文件中[^1]。 #### 示例代码 下面是一个基于段落的简单拆分方法: ```python from docx import Document def split_word_by_paragraph(input_path, output_prefix): # 打开原始Word文档 document = Document(input_path) # 遍历每一个段落并将其写入单独的文件 for index, paragraph in enumerate(document.paragraphs): new_doc = Document() new_doc.add_paragraph(paragraph.text) # 添加当前段落到文档 # 构建输出路径名 output_filename = f"{output_prefix}_part_{index + 1}.docx" # 保存Word文档 new_doc.save(output_filename) # 调用函数进行拆分 split_word_by_paragraph('example.docx', 'output') ``` 此脚本会读取名为 `example.docx` 的源文件,并按每个段落创建独立的小型 .docx 文件[^2]。 如果希望依据更复杂的规则比如章节标题来进行划分,则可能需要解析样式标签或者其他结构化数据作为判断条件之一[^3]。 #### 注意事项 - 上述例子仅考虑基本场景下的逐段分离;实际应用时应视具体需求调整算法。 - 对于大型文档而言,这种方法可能会生成大量小型文件,请提前规划存储空间及命名策略以防冲突或混乱发生。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值