Microsoft Excel是Microsoft為使用Windows和Apple Macintosh操作系統的電腦編寫的一款電子表格軟件。直觀的界面、出色的計算功能和圖表工具,再加上成功的市場營銷,使Excel成為最流行的個人計算機數據處理軟件。 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文件完整路徑名括起來。 還有一段更簡單一些的代碼可以實現: - 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
端口名>驅動程序名>打印機名>文件名>文件名>
Excel整體界面趨于平面化,顯得清新簡潔。流暢的動畫和平滑的過渡,帶來不同以往的使用體驗。
|