VBA代码执行但仅当我逐步执行时

时间:2018-01-12 18:39:21

标签: excel vba process

我使用Close an opened PDF after opening it using FollowHyperlink中的一些代码创建以下代码来打开pdf文件并重命名。代码运行正常但只有我在MsgBox中打破执行" Break Here"并使用F8键进入它。关于它为什么不能自动执行的任何想法?

Sub OpenPDF()
    'Opens PDF Scaned file & saves it to another folder
    '***ErrorHandler***
    On Error Resume Next
    '***Declare Objects****
    Dim objectWMI As Object
    Dim objectProcess As Object
    Dim objectProcesses As Object
    Dim Path As String
    Dim MyDir As String
    '***Opens a new workbook if there are no active workbooks***
    '***There must be an active workbook for FollowHyperlink to function***
    nowbs = Application.Workbooks.Count
    If nowbs = 1 Then
        Application.Workbooks.Add
    Else
    End If
    '***Saves current Excel path
    MyDir = CurDir
    '***Sets path to Ricoh Scans
    PDFDir = "S:\Ricoh Scans"
    ChDir PDFDir
    '***Gets filename for PDF scan
    Path = Application.GetOpenFilename(filefilter:="PDF file (*.pdf), *.pdf")
    '***Opens PDF file***
    ActiveWorkbook.FollowHyperlink Path
    '***Sets Excel as active application
    AppActivate "Microsoft Excel"
    '***Prompts for PO number****
    MyPONum = InputBox("Enter PO Number", "PO Editor", "30500")
    '***If user selects Cancel on inputbox then xl closes Acrobat and exits sub
    If MyPONum = vbNullString Then
        GoTo EndAll
    Else
    End If
    '***Replaces scanned filename with inputbox filename
    PathLen = Len(Path)
    OldName = Mid(Path, 16, PathLen - 19)
    NewName = "S:\Materials Management\Purchase Orders\PO " & MyPONum & ".pdf"
EndAll:
    '***Set Objects***
    Set objectWMI = GetObject("winmgmts://.")
    Set objectProcesses = objectWMI.ExecQuery("SELECT * FROM Win32_Process  WHERE Name = 'Acrobat.exe'") '< Change if you need be ** Was AcroRd32.exe**
    '
    '
    'Code executes fine up to here but must Ctrl + Break at this line
    'and F8 step thru balance of code or it will not work
    '
    '
    MsgBox "Break Here"
    '***Terminate all Open PDFs***
    For Each objectProcess In objectProcesses
        Call objectProcess.Terminate
    Next
    '***Clean Up***
    Set objectProcesses = Nothing
    Set objectWMI = Nothing
    '***Renames scanned file and moves it to Materials Management folder***
    Name Path As NewName
    '***Resets current directory
    ChDir MyDir
End Sub

1 个答案:

答案 0 :(得分:0)

感谢大家的投入。我不是程序员,正如我所说,我使用的是在本网站其他地方发布的代码。这是一个时间问题,这个编辑工作。

    '***Terminate all Open PDFs***
    For Each objectProcess In objectProcesses
    objectProcess.Terminate
    Next
    '***Clean Up***
    Set objectProcesses = Nothing
    Set objectWMI = Nothing
    '***************
    Application.Wait (Now + TimeValue("00:00:02"))
    '***Renames scanned file and moves it to Materials Management folder***
    Name Path As NewName
    '***Resets current directory
    ChDir MyDir

    End Sub