在继续下一行代码之前,我可以让VBA睡一会儿吗?

我编写了一个VBA片段,在我的同事编写的另一个工作簿中调用一个macros。 该macros实际上调用Python来做其他事情,并创build一个新的工作簿。 之后,我需要打开新的工作簿,并做一些其他的事情。 但是,python代码需要一些时间来运行,如果我只是使用

Application.Run "'CollegueWorkbook.xlsm'!pythonmacro" Set wb = Workbooks.Open("NewWorkbook.xlsx") 

我会得到Run-time error '9': Subscript out of range因为时间Set wb = Workbooks.Open("NewWorkbook.xlsx")执行,python代码还没有创build一个新的工作簿,但我猜(它看起来像VBA代码不会等待python线程)

我想知道如何才能让VBA进入睡眠状态,只有在新的工作簿出现时才能继续下一行代码。 或者如果有其他的解决方法?

有两种方法可以暂停脚本。

1) Application.Wait这是在设定的时间继续。

2) Sleep这是为了暂停一段时间。

你正在寻找Application.Wait这等到一个特定的时间,所以如果你想等待10秒,使用Application.Wait Now + TimeValue("0:00:10")你可以考虑一个循环,不得不等待更长的时间:

 Dim retry As Long Set wb = Nothing For retry = 1 To 10 Application.Wait Now + TimeValue("0:00:10") If Dir("NewWorkbook.xlsx") <> "" Then Set wb = Workbooks.Open("NewWorkbook.xlsx") Exit For End If Next retry If wb Is Nothing Then MsgBox "Didn't work..." Else ... End If 

一种方法可能是这样的。 (未testing)

 On Error Resume Next Application.Run "'CollegueWorkbook.xlsm'!pythonmacro" Do While wb Is Nothing Set wb = Workbooks.Open("NewWorkbook.xlsx") Loop