【VBA】把目录及子目录下所有doc/docx转换为pdf格式
Document.SaveAs2 方法 (Word) | Microsoft Learn
https://learn.microsoft.com/zh-cn/office/vba/api/word.wdsaveformat
新建一个1.xls
用office的excel打开1.xls
查看代码
把下面的代码粘贴到右边的代码区域
Sub Main()Dim path As Stringpath = "F:\doc"VisitFolder (path)Debug.Print "操作完成"
End SubSub VisitFolder(fpath As String)Dim testStr As StringDim result As StringDim OFso As Object, baseFolder As Object, ofile As ObjectSet OFso = CreateObject("Scripting.FileSystemObject")Set baseFolder = OFso.GetFolder(fpath)Debug.Print "baseFolder: " & baseFolder' visit sub folderFor Each folder In baseFolder.SubFoldersDebug.Print "folder.path: " & folder.pathCall VisitFolder(folder.path)Next' visit filesFor Each ofile In baseFolder.FilesDebug.Print "ofile.path: " & ofile.pathPosition = InStr(1, ofile.path, ".doc") ' rename .doc to .pdfIf Position > 0 ThentestStr = Mid(ofile.path, 1, Position - 1)result = testStr & ".pdf"Debug.Print resultCall WordToPDF(ofile.path, result)ElseDebug.Print "子字符串未找到"End IfNext
End SubSub Main()Dim path As Stringpath = "F:\doc"VisitFolder (path)Debug.Print "操作完成"
End SubSub VisitFolder(fpath As String)Dim testStr As StringDim result As StringDim OFso As Object, baseFolder As Object, ofile As ObjectSet OFso = CreateObject("Scripting.FileSystemObject")Set baseFolder = OFso.GetFolder(fpath)Debug.Print "baseFolder: " & baseFolder' visit sub folderFor Each folder In baseFolder.SubFoldersDebug.Print "folder.path: " & folder.pathCall VisitFolder(folder.path)Next' visit filesFor Each ofile In baseFolder.FilesDebug.Print "ofile.path: " & ofile.pathPosition = InStr(1, ofile.path, ".doc") ' rename .doc to .pdfIf Position > 0 ThentestStr = Mid(ofile.path, 1, Position - 1)result = testStr & ".pdf"Debug.Print resultCall WordToPDF(ofile.path, result)ElseDebug.Print "子字符串未找到"End IfNext
End Sub' doc/docx save as pdf
Sub WordToPDF(srcpath As String, destpath As String)Dim word As ObjectDim doc As ObjectSet word = CreateObject("Word.Application")Set doc = word.Documents.Open(srcpath) ' doc, docx都可以doc.SaveAs2 Filename:=destpath, FileFormat:=17 ' pdfdoc.Closeword.Quit
End Sub' doc/docx save as pdf
Sub WordToPDF(srcpath As String, destpath As String)Dim word As ObjectDim doc As ObjectSet word = CreateObject("Word.Application")Set doc = word.Documents.Open(srcpath) ' doc, docx都可以doc.SaveAs2 Filename:=destpath, FileFormat:=17 ' pdfdoc.Closeword.Quit
End Sub
创建一些测试的目录和doc
代码的初始化目录设置下要转换的根目录,这里假设以E:\docs2pdfs\doc\为例:
设置好后,点击运行
如果电脑的word可以转换,这个脚本正常一般是可以执行的,执行完的效果会是这样:
对应的目录会将docx生成pdf,其实doc也是可以转成pdf的
有兴趣的话,可以调试下vba脚本。
感谢阅读。