使用VBS实现word、excel批量转换为pdf

使用VBS实现word、excel批量转换为pdf

由于最近我家tiger有这方面的需求,且她单位用的是office 2007的32位系统,网上python转换的方法无法奏效,所以使用通用性还可以的VBS来实现,首先要安装SaveAsPDFandXPS.exe,有这个文件支撑,office才能实现转成pdf,wps是不需要的。然后新建一个txt的文本文件,然后把代码复制进去,保存后把文件的后缀改成 .vbs即可。代码在32位系统已测试过,放心使用。

代码如下:

On Error Resume Next
Const wdExportFormatPDF = 17
Set oWord = WScript.CreateObject("Word.Application")
Set oExcel = WScript.CreateObject("Excel.Application")
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set fds=fso.GetFolder(".")
Set ffs=fds.Files
Set WordIsopen = 0
Set ExcelIsopen = 0
For Each ff In ffs
    If (LCase(Right(ff.Name,4))=".doc" Or LCase(Right(ff.Name,4))="docx" ) And Left(ff.Name,1)<>"~" Then
		WordIsopen = 1
        Set oDoc=oWord.Documents.Open(ff.Path)
        odoc.ExportAsFixedFormat Left(ff.Path,InStrRev(ff.Path,"."))&"pdf",wdExportFormatPDF
	ElseIf 	(LCase(Right(ff.Name,4))=".xls" Or LCase(Right(ff.Name,4))="xlsx" ) And Left(ff.Name,1)<>"~" Then
		ExcelIsopen = 1
		Set oWb = oExcel.Workbooks.Open(ff.Path)
		pdf = Left(ff.Path,InStrRev(ff.Path,".")) & "pdf"
		oExcel.displayalerts=false
		oWb.ExportAsFixedFormat 0,pdf,0,1,1,,,0
    End If
Next

If WordIsopen = 1 Then
	odoc.Close
	oword.Quit
End If

If ExcelIsopen = 1 Then
	oWb.Close
	oExcel.Quit
End If

Set oDoc=Nothing
Set oWord =Nothing
Set oWb=Nothing
Set oExcel =Nothing
MsgBox "All files have been converted to PDF! fishbarbar"

注:
Worksheet.ExportAsFixedFormat 方法 (Excel)用法

你可能感兴趣的:(excel,编程语言)