【VBA】把目录及子目录下所有doc/docx转换为pdf格式

发布于:2025-06-12 ⋅ 阅读:(21) ⋅ 点赞:(0)

Document.SaveAs2 方法 (Word) | Microsoft Learn

https://learn.microsoft.com/zh-cn/office/vba/api/word.wdsaveformat

第一步、新建一个1.xls,用office的excel打开1.xls(别用wps)

第二步、查看代码

第三步、把下面的代码粘贴到右边的代码区域 

Sub Main()
    Dim path As String
    path = "F:\doc"
    VisitFolder (path)
    Debug.Print "操作完成"
End Sub

Sub VisitFolder(fpath As String)
    Dim testStr As String
    Dim result As String
    
    Dim OFso As Object, baseFolder As Object, ofile As Object
    Set OFso = CreateObject("Scripting.FileSystemObject")
    Set baseFolder = OFso.GetFolder(fpath)
    Debug.Print "baseFolder: " & baseFolder
    
    ' visit sub folder
    For Each folder In baseFolder.SubFolders
        Debug.Print "folder.path: " & folder.path
        Call VisitFolder(folder.path)
    Next
    
    ' visit files
    For Each ofile In baseFolder.Files
        Debug.Print "ofile.path: " & ofile.path
        Position = InStr(1, ofile.path, ".doc") ' rename .doc to .pdf
        If Position > 0 Then
            testStr = Mid(ofile.path, 1, Position - 1)
            result = testStr & ".pdf"
            Debug.Print result
            Call WordToPDF(ofile.path, result)
        Else
             Debug.Print "子字符串未找到"
        End If
    Next
End Sub

' doc/docx save as pdf
Sub WordToPDF(srcpath As String, destpath As String)
    Dim word As Object
    Dim doc As Object
    
    Set word = CreateObject("Word.Application")
    Set doc = word.Documents.Open(srcpath) ' doc, docx都可以
    doc.SaveAs2 Filename:=destpath, FileFormat:=17 ' pdf
    
    doc.Close
    word.Quit
End Sub


第四步、创建一些测试的目录和docx

第五步、代码的初始化目录设置下要转换的根目录,这里假设以E:\docs2pdfs\doc\为例:

第六步、设置好后,点击运行

第七步、如果电脑的word可以转换,这个脚本正常一般是可以执行的,执行完的效果会是这样:

 对应的目录会将docx生成pdf,其实doc也是可以转成pdf的

有兴趣的话,可以调试下vba脚本。

感谢阅读。