在异常情况下工作时,循环永不停止

时间:2019-06-24 15:44:05

标签: excel vba loops do-while

我正在尝试自动将文件夹中的所有.pdf文件发送到打印机。

这是我正在尝试的代码


Option Explicit

Declare Function apiShellExecute 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()

Dim filepath As String
Dim currfile As String
Dim wrdApps As Object
Dim wrdDoc As Object

Set wrdApps = CreateObject("Word.Application")
filepath = ActiveWorkbook.Path & "\AIMPRIMER\"
currfile = Dir(filepath & "*.PDF")

Do While currfile <> ""

    PrintFile (filepath + currfile)

    currfile = Dir()
Loop

End Sub


Do While用于浏览文件夹中的所有pdf文件

PrintFile (filepath + currfile)必须将当前文件发送到打印机。

除此以外,我只打印所有.pdf一次,但实际上do while循环无法正常工作,do while循环正在循环且永不停止。

我尝试过:Debug.Print filepath + currfile在这里我一次获得了所有.PDF的路径,但是此路径不会一次发送到打印机。

所以我不明白为什么Debug.Print filepath + currfile运作良好,当我使用PrintFile (filepath + currfile)时,打印机一直打印并且永远都不会停止打印...

1 个答案:

答案 0 :(得分:2)

尽管我无法复制此问题(似乎我的最初尝试确实产生了无限循环,但我无法重现此问题),但API调用似乎抛弃了Dim filepath$, currfile$, item Dim files As New Collection filepath = "C:\debug\" currfile = Dir(filepath & "*.pdf") ' build a list of files to be printed later Do While currfile <> "" files.Add filepath + currfile currfile = Dir() Loop ' print each file in the list we created in previous loop For Each item In files PrintFile currfile Next 。第二次...)。最好先建立文件列表 first

yarn upgrade circuit-sdk