使用VBScript将excel转换为pdf

时间:2017-08-18 13:38:39

标签: excel pdf vbscript

我想用vbscript将pdf转换为excel但是它给我一个错误以下是我的代码:

Option Explicit
Dim objExcel, strExcelPath, objSheet

strExcelPath = "path\file.xlsx"

' Open specified spreadsheet and select the first worksheet.
Set objExcel = CreateObject("Excel.Application")
objExcel.WorkBooks.Open strExcelPath
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)

' Modify a cell.
objSheet.Range("B8").FormulaR1C1  = [sample1]
objSheet.Range("G11").FormulaR1C1 = [sample2]
objSheet.Range("G12").FormulaR1C1 = [sample3]
objSheet.Range("B10").FormulaR1C1 = [sample4]
objSheet.Range("B11").FormulaR1C1 = [sample5]

' Save as Excel.
objExcel.ActiveWorkbook.SaveAs "path\name.xlsx" 
' Problem in saving to pdf
objExcel.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:= "path\name.pdf", _
        Quality:= xlQualityStandard, IncludeDocProperties:=True,_
        IgnorePrintAreas:=False, OpenAfterPublish:=False

objExcel.ActiveWorkbook.Close
objExcel.Application.Quit

如果您在代码中发现任何不良内容,请告诉我。

2 个答案:

答案 0 :(得分:1)

如果其他人有此问题,请替换:

objExcel.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:= "path\name.pdf", _
        Quality:= xlQualityStandard, IncludeDocProperties:=True,_
        IgnorePrintAreas:=False, OpenAfterPublish:=False

使用:

objExcel.ActiveSheet.ExportAsFixedFormat 0, "path\name.pdf" ,0, 1, 0,,,0

这种方式有效!

答案 1 :(得分:0)

您最好在编辑并保存后尝试关闭excel工作簿。您正在尝试将其保存为Pdf,同时更新excel文件。这可能会导致问题。

将其保存为excel后,关闭它并重新打开以导出为Pdf文件。