make excel vba等待直到操作完成

时间:2017-03-22 09:01:59

标签: excel vba excel-vba

我在vba中创建了一个宏来将pdf文件转换为单页。

Sub SplitFiles()

'This needs PDFTK installed

Dim fso As New FileSystemObject
Dim fol As Folder
Dim fil As File
Dim i As Integer
Dim command As String

On Error Resume Next

Set fol = fso.GetFolder("C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Splitsen\")

i = 1

For Each fil In fol.Files
    command = ("C:\Program Files (x86)\PDFtk\bin\pdftk.exe " & fil & " burst output C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Klaar\Klaar" & i & "-%d.pdf")
    Shell command
    i = i + 1
Next fil

Application.Wait (Now + TimeValue("0:00:05"))

Kill "C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Splitsen\*.pdf"
Kill "C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Klaar\*.txt"

End Sub

问题是我必须给出5秒的超时,否则文件会立即被删除,并且不会创建输出。 如何使excel等到所有文件都被处理完毕?

1 个答案:

答案 0 :(得分:1)

谢谢内森,你让我走上了正确的道路:

Sub SplitFiles()

'This needs PDFTK installed

Dim fso As New FileSystemObject
Dim fol As Folder
Dim fil As File
Dim i As Integer
Dim command As String
Dim number As Long

On Error Resume Next

Set fol = fso.GetFolder("C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Splitsen\")
number = fol.Files.Count

i = 1
For Each fil In fol.Files
    command = ("C:\Program Files (x86)\PDFtk\bin\pdftk.exe " & fil & " burst output C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Klaar\Klaar" & i & "-%d.pdf")
    Shell command
    If i = number Then
        Application.Wait (Now + TimeValue("0:00:02"))
        Kill "C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Splitsen\*.*"
        Kill "C:\Users\wanne\OneDrive\Documents\Bijberoep\Scans\Klaar\*.txt"
        Shell ("C:\Program Files (x86)\View and Rename PDF\viewAndRename.exe")
    Else
    i = i + 1
    End If
Next fil

End Sub

这段代码有效,但我首先要声明一个变量,否则它会陷入循环中。

仍然超时2秒,因为并非所有文件都没有延迟删除(可能是因为它们仍在由pdftk处理)