Sub Katana1994() Dim doc1 As Document Dim rng As Range Dim chapterStart As Long Dim chapterEnd As Long Dim chapterTitle As String Dim chapterIndex As Integer Dim newDoc As Document Set doc1 = ActiveDocument chapterIndex = 1 For i = 1 To doc1.Paragraphs.Count Set rng = doc1.Paragraphs(i).Range If rng.Text Like "第篇" Or rng.Text Like "、" Then If chapterStart > 0 Then chapterEnd = rng.Start - 1 doc1.Range(chapterStart, chapterEnd).Select Selection.Copy Set newDoc = Documents.Add() newDoc.Content.Paste newDoc.SaveAs "Chapter" & chapterIndex & " - " & chapterTitle & ".docx" newDoc.Close chapterIndex = chapterIndex + 1 End If chapterTitle = rng.Text chapterStart = rng.End End If Next i End Sub 改进思路,使其识别无格式文本型目录的章节页数寻找对应页码进行划分,自动拆分并另存
时间: 2023-11-27 08:51:51 浏览: 56
这个改进思路涉及到一些比较复杂的技术,需要使用 VBA 编程。具体的实现步骤如下:
1. 定义一个函数,用于获取目录中各章节的起始页码和结束页码。
2. 在主程序中,遍历文档中的每个段落,判断其是否属于目录中的一章。
3. 如果是目录中的一章,则调用函数获取其起始页码和结束页码,并将该章节内容复制到一个新的文档中,并将新文档保存为对应的章节文件。
4. 重复以上步骤,直到所有章节都被拆分为单独的文档。
下面是一个简单的示例代码,用于实现这个功能:
```
Sub SplitChapters()
Dim toc As TableOfContents
Dim tocEntry As Field
Dim chapterStart As Long
Dim chapterEnd As Long
Dim chapterTitle As String
Dim chapterIndex As Integer
Dim newDoc As Document
Set toc = ActiveDocument.TablesOfContents(1)
chapterIndex = 1
For Each tocEntry In toc.Range.Fields
If tocEntry.Result.Text Like "第*" Then
chapterTitle = Replace(tocEntry.Result.Text, Chr(13), "")
chapterStart = toc.Range.Start + tocEntry.Result.Start - 1
chapterEnd = GetChapterEnd(chapterStart)
If chapterEnd > 0 Then
ActiveDocument.Range(chapterStart, chapterEnd).Copy
Set newDoc = Documents.Add()
newDoc.Content.Paste
newDoc.SaveAs "Chapter " & chapterIndex & " - " & chapterTitle & ".docx"
newDoc.Close
chapterIndex = chapterIndex + 1
End If
End If
Next tocEntry
End Sub
Function GetChapterEnd(chapterStart As Long) As Long
Dim pageNum As Integer
With ActiveDocument.Range(chapterStart, ActiveDocument.Range.End)
pageNum = .Information(wdActiveEndPageNumber)
Do While pageNum = .Information(wdActiveEndPageNumber)
.MoveStartUntil vbCr
Loop
GetChapterEnd = .Start - 1
End With
End Function
```
这个程序假设目录中的章节标题都以 "第*" 开头,并且每个章节都占据了一个完整的页面。如果你的目录格式不同,你可能需要修改程序中的一些细节。
阅读全文