通过VBA代码提取页面 - 将提取的页面保存到特定文件夹如果您熟悉VBA,可以使用脚本来自动执行页面提取过程。此方法在处理大型文档时特别有用。
注意:以下代码一次只能提取连续的页面范围。步骤1:按下 Alt + F11 键打开VBA编辑器步骤2:插入新模块在打开的“Microsoft Visual Basic for Applications”窗口中,点击“插入”选项卡,然后选择“模块”。
步骤3:插入代码复制以下代码并将其粘贴到模块窗口中。
Sub SaveSpecifiedPagesAsNewDoc()
'UpdatebyKutools
Dim objNewDoc As Document
Dim objDoc As Document
Dim strFolder As String
Dim strFileName As String
Dim startPage As Long
Dim endPage As Long
Dim startRange As Range
Dim endRange As Range
' Initialize
Set objDoc = ActiveDocument
' Specify the folder path and file name here
strFolder = "C:\Users\AddinsVM001\Desktop\pdf\extract pages" ' Example path
strFileName = "ExtractedPages" ' Example file name
' Specify start and end pages here
startPage = 3
endPage = 4
' Find the range of the specified pages
With objDoc
' Go to the start of the start page
.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=startPage).Select
Set startRange = Selection.Range
' Go to the start of the page after the end page, to get the complete end page
.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=endPage + 1).Select
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Set endRange = Selection.Range
' Define the range from start to end page
Set startRange = .Range(Start:=startRange.Start, End:=endRange.End)
End With
' Copy the defined range
startRange.Copy
' Open a new document to paste the selection
Set objNewDoc = Documents.Add
objNewDoc.Content.Paste
' Save the new document
objNewDoc.SaveAs2 FileName:=strFolder & "\" & strFileName & ".docx"
objNewDoc.Close False
' Clean up
Set objNewDoc = Nothing
Set objDoc = Nothing
Set startRange = Nothing
Set endRange = Nothing
MsgBox "Pages " & startPage & " to " & endPage & " have been extracted to " & strFileName & ".docx"
End Sub 注意:此脚本允许您直接在代码中定义页面范围、文件名和保存路径。请务必修改 strFolder、strFileName、startPage 和 endPage 的值以满足您的需求。一旦宏运行,它将自动将指定的页面保存到新的Word文件中,无需用户交互。步骤4:点击运行按钮或按 F5 键运行代码运行代码后,会弹出一个对话框,告知您页面已提取完成,点击“确定”关闭它。
步骤5:前往文件夹检查页面是否正确提取