通過 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:前往文件夾檢查頁面是否正確提取