如何使用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 LongSub Test_PrintPDF()Dim strFileName As StringstrFileName = “D:\test.pdf”PrintPDf strFileNameEnd SubSub PrintPDf(fnAs String)Dim pdfEXE As StringDim q As StringpdfEXE = ExePath(fn)If pdfEXE = “” ThenMsgBox “没有找到pdf相关的EXE程序.”,vbCritical, “Macro Ending”Exit SubEnd Ifq = “”””Shell q & pdfEXE & q & ” /s/o /h /t ” & q & fn & q, vbHideEnd SubFunction ExePath(lpFile As String) As StringDim lpDirectory As StringDim strExePath As StringDim lrc As LonglpDirectory = “\”strExePath = Space(255)lrc = FindExecutable(lpFile, lpDirectory,strExePath)strExePath = Left$(strExePath,InStr(strExePath, Chr$(0)) – 1)ExePath = strExePathEnd 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 LongPublic Sub PrintFile(ByVal strPathAndFilename As String)Call apiShellExecute(Application.hwnd,”print”, strPathAndFilename, vbNullString, vbNullString, 0)End SubSub test()PrintFile (“D:\test.pdf”)End Sub
温馨提示:答案为网友推荐,仅供参考
相似回答