Microsoft Excel是Microsoft為使用Windows和Apple Macintosh操作系統(tǒng)的電腦編寫的一款電子表格軟件。直觀的界面、出色的計(jì)算功能和圖表工具,再加上成功的市場營銷,使Excel成為最流行的個(gè)人計(jì)算機(jī)數(shù)據(jù)處理軟件。 Q:我想要在VBA中使用代碼來打印指定的PDF文件,如何實(shí)現(xiàn)? A:在之前的文章中,我們介紹了一個(gè)自定義函數(shù)ExePath,可以獲取能夠打開指定文件的EXE程序的路徑。這樣,我們就可以使用EXE程序來打開該文件了。因此,下面的代碼先使用ExePath函數(shù)獲取PDF文件的可執(zhí)行程序路徑,然后使用它來打開指定的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相關(guān)的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命令的參數(shù)如下: /n-啟動(dòng)一個(gè)新的Reader實(shí)例,即使該實(shí)例已經(jīng)打開 /s-不顯示啟動(dòng)界面 /o-不顯示打開文件對話框 /h-以最小化窗口打開 /p <文件名>-打開并直接進(jìn)入打印對話框 /t <文件名> <打印機(jī)名> <驅(qū)動(dòng)程序名> <端口名>-將文件打印到指定的打印機(jī) 3.確保使用雙引號將EXE完整的路徑和PDF文件完整路徑名括起來。 還有一段更簡單一些的代碼可以實(shí)現(xiàn): - 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
端口名>驅(qū)動(dòng)程序名>打印機(jī)名>文件名>文件名>
Excel整體界面趨于平面化,顯得清新簡潔。流暢的動(dòng)畫和平滑的過渡,帶來不同以往的使用體驗(yàn)。
|