【发布时间】:2018-01-12 18:39:21
【问题描述】:
我使用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
【问题讨论】:
-
删除
On Error Resume Next,您可能会收到一条信息性错误消息。如果这没有帮助,您需要告诉我们它是如何失败的。 -
On Error Resume Next不是***ErrorHandler***。它抑制错误并允许代码继续在错误状态下执行,这意味着您的代码正在做出Very Bad Assumption™。 -
如果您的代码不能直接运行,那么这可能表明存在时间问题:某些必需的过程没有及时完成以进行下一步。
-
要解决您遇到的问题,您可能需要在进程终止之间进行某种延迟。尝试在
Call objectProcess.Terminate之前添加Application.Wait(Now + TimeValue("00:00:02"))(您还应该删除Call。 -
感谢大家的意见。我不是程序员,正如我所说,我使用了在本网站其他地方发布的代码。这是时间问题。