怎么使用VBA打印PDF文件?

Q:我想要在VBA中使用代码来打印指定的PDF文件,如何实现?
A:在之前的文章中,我们介绍了一个自定义函数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文件完整路径名括起来 。
【怎么使用VBA打印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

    推荐阅读