VBA:如何等待Excel下载完成?

时间:2019-10-30 10:27:01

标签: excel vba internet-explorer

我有一个宏,它可以导航到一系列网页,从这些页面下载一个excel,然后将数据合并到打开的工作簿中。但是,我的代码失败,因为它找不到新下载的工作簿。当我逐步执行代码时,没有问题。大概我的代码可以继续运行,但是由于新下载的工作簿尚未打开,因此失败了。

我尝试创建一个循环,等待直到下载的工作簿打开,但是似乎该循环运行时无法打开工作簿。

如何在代码中“等待”,直到打开工作簿并且代码可以继续进行? 任何输入表示赞赏,谢谢!

appIE.document.getElementById("_id3805:_id3806:0:_id4177").Click 'click website download button
Dim o As IUIAutomation
Dim e As IUIAutomationElement, download_check As IUIAutomationElement
Set o = New CUIAutomation
Dim h As LongLong
h = appIE.Hwnd
h = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)
If h = 0 Then Exit Sub
Set e = o.ElementFromHandle(ByVal h)
Dim iCnd As IUIAutomationCondition
Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Open")
Dim Button As IUIAutomationElement
Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
Dim InvokePattern As IUIAutomationInvokePattern
Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
InvokePattern.Invoke


Debug.Print "Download Successful, Click OK"

Application.Wait (Now + TimeValue("00:00:02"))
DoEvents
' This part searching active workbook
Dim xWBName As String
Dim GetBook As String
Dim xWb As Workbook

Do Until Application.Workbooks.Count > 1
'    'I am waiting for something to happen
    DoEvents
    Application.Wait (Now + TimeValue("00:00:01"))
    Sleep 1000
Loop

For Each xWb In Application.Workbooks
    'xWBName = xWb.Name 'xWBName & xWb.Name & vbCrLf
    DoEvents
    If InStr(xWb.Name, "Data") Then
     GetBook = xWb.Name
    End If
Next
DoEvents
'Activate the required workbook
**Set wb2 = Workbooks(GetBook)**

1 个答案:

答案 0 :(得分:0)

我认为您使用sleep和doEvents的方法是解决此问题的好方法。首先打开下载的工作簿,检查睡眠循环是否存在,然后退出循环。

If Dir(pathToFile) <> "" Then
    'File has been found
end if

编辑: 我没有看到您要打开文件的部分。 在您的情况下发生的顺序是: 1.下载文件 2.等待循环,在其中检查文件是否已下载 3.打开文件

睡眠循环可能看起来像这样:

'Download the file here

dim fileFound as boolean
while not fileFound
    sleep(1000)
    DoEvents
    If Dir(pathToFile) <> "" Then
        fileFound = true
    end if
wend

'Open the file here