2011-12-16 69 views
2

有没有办法强制excel始终打印PDF格式的文件?出于某种原因,我发现的标准代码(在本网站和其他网站上)似乎不起作用。只允许在Excel 2007/2010中保存为PDF

下面是我使用的代码:

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

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

+1

什么是你的代码做,而不是工作? – 2011-12-16 01:07:18

+0

确保您的输入框应使用其名称捕获文件的完整路径,例如C:\ Users \ SONY \ Desktop \ Book1.pdf – Ian 2011-12-20 04:23:11

+0

如果我没有输入完整路径,是不是默认为当前路径?一旦我开始工作,我打算覆盖默认路径,所以我只关心名称。 – Jay 2011-12-20 18:21:15

回答

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 
0

很久以前,我使用了与Excel结合的开源PDFPrinter。这里是我写的一些代码,似乎可以做你想做的事。也许你可以用它作为你自己的解决方案的开始?

'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

问候,

罗伯特Ilbrink