利用Word VBA实现多个Word转PDF

本文介绍了一个使用VBA编写的Word宏,它能自动选择文件夹中的所有.doc文档,将其转换为.docx格式并进一步转存为PDF,同时删除原始.doc文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        在word VBA的模块里写入以下代码,可实现选中文件夹的所有doc格式的word自动转换成docx格式,再转换成PDF,转换成功后doc文件自动删除。

Private Sub ConvertPDF_Click()

Application.ScreenUpdating = False

Dim sDocPath As String

Dim MyDoc As Object

Dim sNewPath As String

Dim MyDocx As Object

Dim FileCount As Integer

Dim i As Integer

Dim sDocName As String

Dim sArr(100) As String

Dim sDocxName As String

With Application.FileDialog(msoFileDialogFolderPicker)

    .Title = "选择需要PDF转换的文件夹"

    If .Show = -1 Then

      sDocPath = .SelectedItems(1)

    Else

      Exit Sub

    End If

End With

sDocName = Dir(sDocPath & "\*.doc")

Do While sDocName <> ""

    If (Right(sDocName, 3) = "doc") Then

        sArr(FileCount) = sDocName

        If sDocName = "" Then

            Exit Do

        End If

        FileCount = FileCount + 1

    End If

    sDocName = Dir

Loop

For i = 0 To FileCount - 1   

    Set MyDoc = Documents.Open(sDocPath & "\" & sArr(i), , , , , , , , , , , msoFalse)

    sNewPath = VBA.Strings.Replace(sDocPath & "\" & sArr(i), ".doc", ".docx")

    If Dir(sNewPath, vbDirectory) = "" Then

        MyDoc.SaveAs2 filename:=sNewPath, FileFormat:=wdFormatDocumentDefault                'MyDoc会变为doc

    End If

    sDocxName = Dir(sNewPath)

    Set MyDocx = Documents.Open(sDocPath & "\" & sDocxName, , , , , , , , , , , msoFalse)

    sNewPath = VBA.Strings.Replace(sDocPath & "\" & sDocxName, ".docx", ".pdf")

    MyDocx.SaveAs2 filename:=sNewPath, FileFormat:=wdFormatPDF                               'MyDocx仍为docx

    If Right(MyDoc, 4) <> "docx" Then

        MyDoc.Close SaveChanges:=False

        MyDocx.Close SaveChanges:=False

    Else

        MyDoc.Close SaveChanges:=False

    End If

    Kill (VBA.Strings.Replace(sDocPath & "\" & sArr(i), ".doc", ".docx"))   

    Set MyDoc = Nothing

    Set MyDocx = Nothing

Next

   Application.ScreenUpdating = True

End Sub

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值