You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA按名称顺序打印PDF文件代码修正求助

按文件名顺序打印PDF的VBA代码修正

原代码的问题在于Dir函数返回文件的顺序是系统默认排序规则(不一定是严格的文件名字母/数字顺序),要实现按文件名排序打印,需要先把所有PDF文件名收集到数组,排序后再逐个处理。

修正后的代码如下:

Sub Send_to_Printer_in_Sequence()
    Dim way As String, pdfName As String
    Dim pdfFiles() As String
    Dim fileCount As Integer, i As Integer, j As Integer
    Dim temp As String
    
    Application.ScreenUpdating = False
    
    ' 获取文件所在路径
    way = ThisWorkbook.Path & Application.PathSeparator
    
    ' 收集所有PDF文件名到数组
    fileCount = 0
    pdfName = Dir(way & "*.pdf")
    Do While pdfName <> ""
        fileCount = fileCount + 1
        ReDim Preserve pdfFiles(1 To fileCount)
        pdfFiles(fileCount) = pdfName
        pdfName = Dir
    Loop
    
    ' 对文件名数组进行冒泡排序(不区分大小写)
    For i = 1 To fileCount - 1
        For j = i + 1 To fileCount
            If UCase(pdfFiles(i)) > UCase(pdfFiles(j)) Then
                temp = pdfFiles(i)
                pdfFiles(i) = pdfFiles(j)
                pdfFiles(j) = temp
            End If
        Next j
    Next i
    
    ' 按排序后的顺序逐个打印PDF
    For i = 1 To fileCount
        CreateObject("Shell.Application").Namespace(0).ParseName(way & pdfFiles(i)).InvokeVerb ("Print")
        Application.Wait Now + TimeSerial(0, 0, 4)
    Next i
    
    ' 尝试关闭Acrobat Reader(忽略未打开的情况)
    On Error Resume Next
    AppActivate "Acrobat Reader", True
    SendKeys "%{F4}", True
    Application.Wait Now + TimeSerial(0, 0, 3)
    On Error GoTo 0
    
    Application.ScreenUpdating = True
    MsgBox "所有PDF已发送至打印机。"
End Sub

关键修改说明:

  • 收集文件到数组:先将所有PDF文件名存入数组,摆脱Dir函数的默认顺序限制
  • 文件名排序:用冒泡排序对数组内的文件名做不区分大小写的排序,确保严格按字母/数字顺序排列
  • 遍历排序数组打印:按照排序后的顺序逐个执行打印操作
  • 错误处理优化:调整错误处理逻辑,避免因Acrobat Reader未打开导致的运行报错

内容的提问来源于stack exchange,提问作者Mehmet Şeker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:38:22