下面的VBA代码可以实现,具体使用方法:
1. 打开Word,按下 Alt + F11 打开VBA编辑器。
2. 在“项目”窗口中,右键点击“这个文档”,选择“插入” -> “模块”。
3. 将上述代码复制并粘贴到模块窗口中。
4. 修改代码中的 docPath变量,将其设置为你的Word文档所在的文件夹路径。
5. 运行这个宏(可以按下 F5 键或点击“运行”按钮)。
[Asm] 纯文本查看 复制代码 Sub DeleteLastPagePictures(folderPath As String)
Dim fileSystemObject As Object
Dim folder As Object
Dim file As Object
Dim wdApp As Word.Application
Dim doc As Word.Document
Dim lastPage As Word.Range
Dim shp As Word.InlineShape
' 创建 FileSystemObject 对象
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
' 设置要遍历的文件夹对象
Set folder = fileSystemObject.GetFolder(folderPath)
' 设置 Word 应用程序对象
Set wdApp = Word.Application
wdApp.Visible = False
' 遍历文件夹中的每个文件
For Each file In folder.Files
' 检查文件是否为 Word 文档
If Right(file.Name, 4) = ".doc" Or Right(file.Name, 5) = ".docx" Then
' 打开文档
Set doc = wdApp.Documents.Open(file.Path)
' 初始化图片计数器
imgCount = 0
' 从文档的末尾开始向前遍历所有InlineShape对象
For i = doc.InlineShapes.Count To 1 Step -1
Set lastImage = doc.InlineShapes(i)
' 增加图片计数器
imgCount = imgCount + 1
' 删除找到的最后一张
lastImage.Delete
' 退出循环
Exit For
Next i
' 保存并关闭文档
doc.Save
doc.Close
End If
Next file
' 遍历子文件夹
Dim subFolder As Object
For Each subFolder In folder.SubFolders
DeleteLastPagePictures subFolder.Path ' 递归调用
Next subFolder
' 清理对象
Set fileSystemObject = Nothing
Set folder = Nothing
Set file = Nothing
Set wdApp = Nothing
Set doc = Nothing
Set lastPage = Nothing
Set shp = Nothing
End Sub
Sub ToDeleteLastPagePictures()
Dim docPath As String
' 调用 DeleteLastPagePictures 过程,并传递文件夹路径作为参数
docPath = "G:\tt\doc\"
DeleteLastPagePictures docPath
MsgBox "处理完成!"
End Sub |