2011-12-16 34 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