仅允许在Excel 2007/2010中保存为PDF

时间:2011-12-16 00:50:16

标签: excel pdf printing

有没有办法强制excel始终以PDF格式打印文件?出于某种原因,我发现的标准代码(在此网站和其他网站上)似乎不起作用。

这是我正在使用的代码:

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
cFileName, Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False

我有一个简单的输入框来捕获文件名,我想阻止他们做其他事情。理想情况下,我想将此代码放入我的BeforeSave事件和我的BeforePrint事件中,这样他们唯一能做的就是打印到PDF。这可能吗?

2 个答案:

答案 0 :(得分:0)

您是否收到此类错误或运行代码?

“自动化错误:调用的对象已与其客户端断开连接”Excel 2000中的错误消息

如果是,请查看下面的链接

http://support.microsoft.com/kb/813120

使用工作表中的以下代码

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Macro1
    End Sub

在新模块中添加以下代码

    Sub Macro1()
    cfilename = "C:\Users\SONY\Desktop\Book1.pdf" 'you can use the input box method to get the desired file name and location
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
            cfilename, Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
            False
    End Sub

答案 1 :(得分:0)

很久以前我将opensource PDFPrinter与Excel结合使用。以下是我编写的一些代码,它们似乎可以满足您的需求。也许您可以将此作为自己解决方案的开端?

'Print the saved file as a pdf in the same directory

KTCurrentFilePath = ActiveWorkbook.Path 'Store current FilePath

'Define Variables for PDF printjob

Dim pdfjob As Object

Dim KTPDFName As String

Dim KTPDFPath As String

Dim KTPCurrentPrinter As String

'Set Variable Values

KTPDFName = Range("MyPDFName").Value & ".pdf"

KTPDFPath = ActiveWorkbook.Path & Application.PathSeparator

KTPCurrentPrinter = Application.ActivePrinter

'Check if worksheet is empty and exit if so

If IsEmpty(ActiveSheet.UsedRange) Then Exit Sub

'Start PDF Engine

Set pdfjob = CreateObject("PDFCreator.clsPDFCreator")

On Error GoTo 0

With pdfjob

    If .cStart("/NoProcessingAtStartup") = False Then

        MsgBox "Can't initialize PDFCreator.", vbCritical + _

            vbOKOnly, "PrtPDFCreator"

            Application.ActivePrinter = KTPCurrentPrinter

        Exit Sub

    End If

    .cOption("UseAutosave") = 1

    .cOption("UseAutosaveDirectory") = 1

    .cOption("AutosaveDirectory") = KTPDFPath

    .cOption("AutosaveFilename") = KTPDFName

    .cOption("AutosaveFormat") = 0    ' 0 = PDF

    .cClearCache

End With

'Print the document to PDF

ActiveSheet.PrintOut copies:=1, ActivePrinter:="PDFCreator"

'Wait until the print job has entered the print queue

Do Until pdfjob.cCountOfPrintjobs = 1

    DoEvents

Loop

pdfjob.cPrinterStop = False

'Wait until PDF creator is finished then release the objects

Do Until pdfjob.cCountOfPrintjobs = 0

    DoEvents

Loop

pdfjob.cClose

Set pdfjob = Nothing

'Reset Printer to default

Application.ActivePrinter = KTPCurrentPrinter

End Sub

KTCurrentFilePath = ActiveWorkbook.Path 'Store current FilePath 'Define Variables for PDF printjob Dim pdfjob As Object Dim KTPDFName As String Dim KTPDFPath As String Dim KTPCurrentPrinter As String

此致

罗伯特·伊尔布林克