2016-06-23 50 views
0

得到這個偉大的VBA 1行命令打印外部文件而不打開它。VBA打印外部文件在循環中不工作

CreateObject("Shell.Application").Namespace(0).ParseName("F:\testprint.pdf").InvokeVerb ("Print") 

完美的作品!現在,我試圖插入一個循環來以特定順序打印一堆文件,並打印第一個文件並停止,沒有給出錯誤,但宏似乎陷入了一段時間。

我的代碼:

Sub PrintFile() 

    For r = 1 To 3 

     FileToPrint = Sheet7.Cells(1 + r, 5).Value 

     If FileToPrint = "" Then 
      GoTo MainLoop 
     Else 
      Debug.Print r; " - "; FileToPrint 
      CreateObject("Shell.Application").Namespace(0).ParseName(FileToPrint).InvokeVerb ("Print") 
      Debug.Print r; " --- "; FileToPrint 
     End If 
     MainLoop: 
    Next r 

End Sub 

任何建議,想法?

感謝

+0

你可以在for循環之外聲明一次對象並重用它嗎? – Jules

回答

0

您需要啓動另一個打印作業之前完成第一個打印作業。

#If VBA7 Then 
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems 
#Else 
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems 
#End If 

Sub PrintFile() 
    Dim objShell, WshShell 
    Set objShell = CreateObject("Shell.Application") 


    For r = 1 To 3 

     FileToPrint = Sheet7.Cells(1 + r, 5).Value 

     If FileToPrint = "" Then 
      GoTo MainLoop 
     Else 
      Debug.Print r; " - "; FileToPrint 
      objShell.Namespace(0).ParseName(FileToPrint).InvokeVerb ("Print") 
      Sleep 300 
      Debug.Print r; " --- "; FileToPrint 
     End If 
MainLoop: 
    Next r 

End Sub 
+0

感謝@ thomas,通過延遲每一輪'for'解決了我不按順序打印的問題。我的整個宏gettting卡住的問題似乎是由於其中一個文件是.xlsm格式,所以我用另一種方式解決了它的處理問題。 – Diego