学习Excel技术,关注微信公众号:
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 strFileNameEnd 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, vbHideEnd 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 = 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 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
注:本文学习整理自www.ozgrid.com/forum,在该论坛中,有很多实用的问题解答,可以在帮助我们答疑解惑的同时提高VBA编程能力。