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
猜你喜歡
- Excel是怎么控制公式計算的
- 標識并使用VBA代碼識別特定的工作簿
- 使用VBA讀寫Windows注冊表
- excel圖表怎么記錄指定單元格每次修改的時間?
- excel使用VBA獲取能夠打開指定文件的EXE程序
- 淘寶地推補單物流怎么發貨?需要注意哪些細節?
- 淘寶開票信息在哪里?淘寶發票如何使用?
- 閑魚賣家最遲幾天發貨?怎么與買家溝通?
- 淘寶號為什么會被降權?降權了怎么解決?
- 閑魚沒發貨可以退款嗎?怎么退貨?
