問與答71: 如何使用VBA列印PDF文件?

  • 2019 年 11 月 22 日
  • 筆記

excelperfect

Q:我想要在VBA中使用程式碼來列印指定的PDF文件,如何實現?

A:在《VBA小技巧04:使用VBA獲取能夠打開指定文件的EXE程式》中,我們介紹了一個自定義函數ExePath,可以獲取能夠打開指定文件的EXE程式的路徑。這樣,我們就可以使用EXE程式來打開該文件了。因此,下面的程式碼先使用ExePath函數獲取PDF文件的可執行程式路徑,然後使用它來打開指定的PDF文件。

程式碼如下:

DeclareFunction FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _  (ByVal lpFileAs String, ByVal lpDirectory As String, ByVal lpResult As String) As Long    Sub Test_PrintPDF()    Dim strFileName As String    strFileName = "D:test.pdf"    PrintPDf strFileName  End Sub    Sub PrintPDf(fnAs String)    Dim pdfEXE As String    Dim q As String      pdfEXE = ExePath(fn)    If pdfEXE = "" Then      MsgBox "沒有找到pdf相關的EXE程式.",vbCritical, "Macro Ending"      Exit Sub    End If      q = """"      Shell q & pdfEXE & q & " /s/o /h /t " & q & fn & q, vbHide  End Sub    Function ExePath(lpFile As String) As String     Dim lpDirectory As String     Dim strExePath As String     Dim lrc As Long     lpDirectory = ""     strExePath = Space(255)     lrc = FindExecutable(lpFile, lpDirectory,strExePath)     strExePath = Left$(strExePath,InStr(strExePath, Chr$(0)) - 1)     ExePath = strExePath  End Function

程式碼中:

1.使用變數strFileName指定了所要列印的PDF文件的完整路徑名。

2.對於AcroRd32.exe,傳遞給Shell命令的參數如下:

/n-啟動一個新的Reader實例,即使該實例已經打開

/s-不顯示啟動介面

/o-不顯示打開文件對話框

/h-以最小化窗口打開

/p <文件名>-打開並直接進入列印對話框

/t <文件名> <印表機名> <驅動程式名> <埠名>-將文件列印到指定的印表機

3.確保使用雙引號將EXE完整的路徑和PDF文件完整路徑名括起來。

還有一段更簡單一些的程式碼可以實現:

Declare FunctionapiShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _      ByVal hwnd As Long, _      ByVal lpOperation As String, _      ByVal lpFile As String, _      ByVal lpParameters As String, _      ByVal lpDirectory As String, _      ByVal nShowCmd As Long) _      As Long    Public Sub PrintFile(ByVal strPathAndFilename As String)      Call apiShellExecute(Application.hwnd,"print", strPathAndFilename, vbNullString, vbNullString, 0)  End Sub    Sub test()      PrintFile ("D:test.pdf")  End Sub

Tags: