vba 实现Word文档的批量转换为PDF

如图,在vba编辑窗口,选择“工具--》引用”

sub batchConvert2pdf()

'需要转换的word文档的个数

dim total as Integer

'定义文件名数组:数组的个数根据需要进行设置

 

Dim fns(total) As String

     fns(0) = "d:\doc\1.docx"

'.....................

fns(total-1) = "d:\doc\n.docx"

     '定义PDF文件名和Word文件名

Dim pdf, doc As String

'定义文件对象,用于file操作
Dim fso As New Scripting.FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")

Dim i As Integer
For i = 0 To total-1

    doc = fns(i)  
    pdf = changeExtension(doc,"pdf")

'如果pdf已经存在,进行下一个
    If fso.FileExists(pdf) Then GoTo endflag   

    If fso.FileExists(doc) Then GoTo endflag   
    '打开Word
    Documents.Open doc
    
    On Error GoTo mflag
    ActiveDocument.Convert
    ActiveDocument.Save
mflag:
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
        pdf _
        , ExportFormat:=wdExportFormatPDF, OpenAfterExport:=false, OptimizeFor:= _
        wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
        Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False
    ActiveDocument.Save
    ActiveDocument.Close
    
endflag:   Next i

end sub

 

'改变扩展名
Function changeExtension(filename, ext)
 Dim extension As String
 extension = IIf((Mid(ext, 1, 1) = "."), Mid(ext, 2), ext)
 Dim loc As Integer
 loc = InStrRev(filename, "\")
 Dim dotloc As Integer
 dotloc = InStr(loc, filename, ".")
 Dim flen As Integer
 flen = Len(filename)
 If loc = flen Then
    changeExtension = ""
    Exit Function
 End If
 If dotloc < loc Then
   changeExtension = filename + "." + extension
    Exit Function
 End If
 changeExtension = Mid(filename, 1, dotloc) + extension
End Function

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值