使用Application.ontime循环

时间:2015-08-17 21:36:53

标签: excel vba excel-vba pdf

我正在尝试循环下面的函数。目标是将PDF文件复制并粘贴到单独的工作表中。基本的复制和粘贴功能可行,但是,当我尝试循环时,它会执行每个Private Sub 3次,然后再转到下一个Private Sub。例如,在Private Sub SecondStep尝试连续三次从同一PDF中复制和粘贴之前。

任何人都可以帮忙解决如何正确循环吗?

Sub PDF_Copy_Paste_Loop()

Dim AdobeApp As String
Dim AdobeFile As String
Dim StartAdobe
Dim myfile As String
Dim i As Integer

i = 1

Do While i < 4


AppActivate "Tests - Excel"

Workbooks("tests").Sheets("Sheet1").Activate

myfile = Cells(i, 1)

AdobeApp = "C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\Acrobat.exe"
AdobeFile = "C:\Users\klanders\Desktop\" & myfile & ".pdf"

StartAdobe = Shell("" & AdobeApp & " " & AdobeFile & "", 1)

Application.OnTime Now + TimeValue("00:00:02"), "FirstStep2"
i = i + 1

Loop



End Sub

Private Sub FirstStep()

SendKeys ("^a")
SendKeys ("^c")

Application.OnTime Now + TimeValue("00:00:04"), "SecondStep2"

End Sub

Private Sub SecondStep()

AppActivate "Book1 - Excel"
Workbooks("Book1").Sheets("Sheet" & i).Activate

Range("A1").Select

SendKeys ("^v")

Application.OnTime Now + TimeValue("00:00:06"), "ThirdStep2"


End Sub

Private Sub ThirdStep()

Sheets.Add

End Sub

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助(未经测试)

Option Explicit

Sub PDF_Copy_Paste_Loop()
    Dim AdobeApp As String, AdobeFile As String
    Dim i As Long, ws As Worksheet, wb As Workbook

    'out of the loop (static value)
    AdobeApp = "C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\Acrobat.exe"

    Set wb = Workbooks("Book1")
    Set ws = Workbooks("tests").Worksheets("Sheet1")
    i = 1
    Do While i < 4
        AdobeFile = "C:\Users\klanders\Desktop\" & ws.Cells(i, 1).Value2 & ".pdf"
        Shell AdobeApp & " " & AdobeFile, 1
        Application.Wait Now + TimeValue("0:00:02") 'pause 2 seconds
            SendKeys "^a"
            SendKeys "^c"
        Application.Wait Now + TimeValue("0:00:02")
            AppActivate "Book1 - Excel"
            wb.Worksheets(i).Range("A1").Select
            SendKeys "^v"
        Application.Wait Now + TimeValue("0:00:02")
        wb.Worksheets.Add
        i = i + 1
    Loop
End Sub