Option Explicit
'/ Activate these References;
' 1. Microsoft scripting runtime
' 2. Microsoft shell conrols and automation
Dim rng_Page As Word.Range
Dim rng_Delete As Word.Range
Dim rng_LastPage As Word.Range
Sub RemovePages()
Dim MyDir As String
Dim Key As Variant
Dim MyDoc As Word.Document
MyDir = 'Parent folder path
For Each Key In FilesFromFolder(MyDir)
Set MyDoc = Documents.Open(FileName:=Key, Visible:=False)
FirstSix(MyDoc).Delete
LastPage(MyDoc).Delete
MyDoc.Close wdSaveChanges, wdOriginalDocumentFormat
Next
End Sub
'/ Returs first six pages in the document
'/ This could be errorprone, bookmark "\page" can return incorrectly if tables etc. spans several pages
Private Function FirstSix( _
WordDoc As Word.Document _
) As Word.Range
On Error Resume Next
Dim int_Page As Long: int_Page = 1
Do While int_Page <= 6
If Err.Number <> 0 Then Exit Do
With WordDoc
Set rng_Page = .GoTo(What:=wdGoToPage, Name:=int_Page)
Set rng_Page = rng_Page.GoTo(What:=wdGoToBookmark, Name:="\page")
If int_Page = 1 Then
Set rng_Delete = rng_Page
Else
rng_Delete.SetRange rng_Delete.Start, rng_Page.End
End If
End With
int_Page = int_Page + 1
Loop
Set FirstSix = rng_Delete
End Function
Private Function LastPage( _
WordDoc As Word.Document _
) As Word.Range
With WordDoc
Set rng_LastPage = .GoTo(What:=wdGoToPage, Name:=WordDoc.Range.Information(wdNumberOfPagesInDocument))
Set rng_LastPage = rng_LastPage.GoTo(What:=wdGoToBookmark, Name:="\page")
rng_LastPage.SetRange rng_LastPage.Start - 1, rng_LastPage.End
End With
Set LastPage = rng_LastPage
End Function
'/ Add File if file type contains the phrase "Word"
Private Function FilesFromFolder( _
ParentDir As String _
) As Scripting.Dictionary
Dim obj_Shell As New Shell32.Shell
Dim Folder As Shell32.Folder
Dim Item As Shell32.FolderItem
Dim dict_Temp As New Scripting.Dictionary
If ParentDir = "" Then Exit Function
For Each Item In obj_Shell.Namespace(ParentDir).Items
If Item.IsFolder = True Then
Call FilesFromFolder(Item.Path) '/ Include files in subfolders
Else
If dict_Temp.Exists(Item.Name) = False Then
If InStr(1, Item.Type, "Word", vbTextCompare) >= 1 Then
dict_Temp.Add Item.Path, Item
End If
End If
End If
Next
Set FilesFromFolder = dict_Temp
End Function