文章背景:在工作中,有时候想通过VBA批量打印pdf文件,可以调用Windows的Shell命令来完成。下面介绍两种方案。
1 ShellExecute
VBA代码如下:
代码语言:javascript复制Option Explicit
' 批量打印PDF文件
#If VBA7 And Win64 Then
Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As LongPtr, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As LongPtr
#Else
Public Declare Function ShellExecute 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
#End If
Sub 批量打印PDF文件_ShellExecute()
Dim myPath As String
Dim s As String
Dim i As Long
Dim waitTime As Double
' 设置等待时间(秒)
waitTime = 2
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Add "所有PDF文件", "*.pdf", 1 ' PDF文件
.AllowMultiSelect = True ' 多选
If .Show Then
' 打印每个选中的PDF文件
For i = 1 To .SelectedItems.Count
s = .SelectedItems(i)
ShellExecute Application.hwnd, "print", s, vbNullString, vbNullString, 0 ' SW_HIDE
' 等待打印完成
Application.Wait Now TimeValue("0:00:" & waitTime)
Next i
Else
Exit Sub
End If
End With
Application.ScreenUpdating = True
MsgBox "PDFs printed successfully.", vbInformation
End Sub
2 Shell
VBA代码如下:
代码语言:javascript复制Option Explicit
Sub 批量打印PDF文件_shell()
Dim myPath As String
Dim strFilePath As String
Dim i As Long
Dim waitTime As Double
Dim acrobatPath As String, printCommand As String
' 设置等待时间(秒)
waitTime = 2
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Add "所有PDF文件", "*.pdf", 1 ' PDF文件
.AllowMultiSelect = True ' 多选
If .Show Then
' 设置Adobe Acrobat的路径(根据您安装的路径进行调整)
acrobatPath = "C:Program FilesAdobeAcrobat DCAcrobatAcrobat.exe"
' 打印每个选中的PDF文件
For i = 1 To .SelectedItems.Count
strFilePath = .SelectedItems(i)
' 构建打印命令
printCommand = """" & acrobatPath & """ /t """ & strFilePath & """"
' 使用Shell函数运行打印命令
Shell printCommand, vbHide
' 等待打印完成,等待时间可以根据实际情况调整。
Application.Wait Now TimeValue("0:00:" & waitTime)
Next i
Else
Exit Sub
End If
End With
Application.ScreenUpdating = True
MsgBox "PDFs printed successfully.", vbInformation
End Sub
3 注意点
(1)ShellExecute
和Shell
命令都是异步执行的,这意味着当你发出打印命令时,VBA代码不会等待前一份pdf打印完成,就会继续执行下一份pdf文件的打印。这可能会导致打印多份PDF文件时出现打印顺序乱序的问题。
(2)除了使用等待时间或复杂的 API 调用外,确实没有直接的简单有效方法来在 VBA 中实现同步打印 PDF 文件。VBA 本身并没有提供直接的同步打印功能,而且对于打印任务的管理和状态跟踪也有一定的局限性。
参考资料:
[1] 使用VBA打印PDF文件(https://blog.csdn.net/taller_2000/article/details/134213599)
[2] 批量打印PDF文件时如何设置打印份数(https://club.excelhome.net/thread-1597713-1-1.html)
延伸阅读:
[1] Python: PDF文件的批量顺序打印