本帖最后由 mormas 于 2025-1-26 22:12 编辑
文档较大时可能速度较慢,添加进度条和取消机制
[Visual Basic] 纯文本查看 复制代码 Sub CreateHeadingIndexTableWithProgress()
Dim doc As Document
Dim newDoc As Document
Dim table As Table
Dim headingRange As Range
Dim headingText As String
Dim headingLevel As Integer
Dim i As Long
Dim rowIndex As Long
Dim totalParagraphs As Long
Dim progress As Single
Dim cancelFlag As Boolean
' 获取当前文档
Set doc = ActiveDocument
totalParagraphs = doc.Paragraphs.Count
' 创建进度条窗体
Dim progressForm As Object
Set progressForm = CreateProgressForm()
progressForm.Show vbModeless
' 创建一个新文档用于存放标题索引表
Set newDoc = Documents.Add
newDoc.Content.Text = "标题索引表" & vbCrLf & vbCrLf
newDoc.Content.InsertAfter Text:="级别" & vbTab & "标题内容" & vbCrLf
' 遍历文档中的所有段落
For i = 1 To totalParagraphs
' 更新进度条
progress = i / totalParagraphs
progressForm.UpdateProgress progress, "正在处理段落 " & i & " / " & totalParagraphs
' 检查是否取消
If progressForm.CancelRequested Then
cancelFlag = True
Exit For
End If
' 检查段落是否使用了标题样式
If doc.Paragraphs(i).Range.Style.Type = wdStyleTypeParagraph Then
If Left(doc.Paragraphs(i).Range.Style.NameLocal, 5) = "标题" Then
' 获取标题级别
headingLevel = Val(Mid(doc.Paragraphs(i).Range.Style.NameLocal, 6))
' 获取标题文本
headingText = doc.Paragraphs(i).Range.Text
headingText = Left(headingText, Len(headingText) - 1) ' 去掉末尾的换行符
' 将标题级别和内容写入新文档
newDoc.Content.InsertAfter Text:=headingLevel & vbTab & headingText & vbCrLf
End If
End If
Next i
' 关闭进度条窗体
Unload progressForm
' 如果用户取消操作
If cancelFlag Then
newDoc.Close SaveChanges:=wdDoNotSaveChanges
MsgBox "操作已取消。", vbInformation
Exit Sub
End If
' 将内容转换为表格
newDoc.Content.ConvertToTable Separator:=vbTab, NumColumns:=2
' 设置表格样式
Set table = newDoc.Tables(1)
With table
.Style = "网格表"
.Columns(1).Width = 50
.Columns(2).Width = 400
.Rows(1).Range.Font.Bold = True ' 表头加粗
End With
' 提示完成
MsgBox "标题索引表已生成!", vbInformation
End Sub
Function CreateProgressForm() As Object
Dim userForm As Object
Dim progressBar As Object
Dim cancelButton As Object
Dim label As Object
' 创建用户窗体
Set userForm = VBA.UserForms.Add("ProgressForm")
With userForm
.Caption = "生成标题索引表"
.Width = 300
.Height = 120
End With
' 添加标签
Set label = userForm.Controls.Add("Forms.Label.1", "ProgressLabel")
With label
.Caption = "正在初始化..."
.Left = 10
.Top = 10
.Width = 280
.Height = 20
End With
' 添加进度条
Set progressBar = userForm.Controls.Add("Forms.ProgressBar.1", "ProgressBar")
With progressBar
.Left = 10
.Top = 40
.Width = 280
.Height = 20
End With
' 添加取消按钮
Set cancelButton = userForm.Controls.Add("Forms.CommandButton.1", "CancelButton")
With cancelButton
.Caption = "取消"
.Left = 110
.Top = 70
.Width = 80
.Height = 30
End With
' 设置取消标志
userForm.CancelRequested = False
' 绑定取消按钮事件
With cancelButton
.OnAction = "CancelProgress"
End With
' 返回用户窗体
Set CreateProgressForm = userForm
End Function
Sub CancelProgress()
Dim progressForm As Object
Set progressForm = VBA.UserForms("ProgressForm")
progressForm.CancelRequested = True
progressForm.Hide
End Sub |