VBA从IE下载文件:单击“保存”后出现第二个弹出窗口

时间:2019-12-04 14:55:26

标签: excel vba

我正在自动化一个过程,必须从Internet Explorer的网站上下载文件。我有以下代码,一旦下载弹出,就单击“保存”按钮。

Sub thing()

'Find download message and click Save to download file
Dim o As IUIAutomation
Set o = New CUIAutomation
Dim Completed As String
Dim h As Long
Dim ie As InternetExplorer
Dim html As HTMLDocument

Sleep 1000
Set ie = CreateObject("InternetExplorer.application")
Do
    h = ie.hwnd
    h = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)

    If h <> 0 Then
        Dim count As Long
        count = 0
        Exit Do
    Else
        Sleep 100
        count = count + 1
    End If
Loop

Dim e As IUIAutomationElement
Set e = o.ElementFromHandle(ByVal h)

Dim iCnd As IUIAutomationCondition
Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Save")

Dim Button As IUIAutomationElement
Set Button = e.FindFirst(TreeScope_Subtree, iCnd)

Sleep 1000

Do
    On Error Resume Next
    Dim InvokePattern As IUIAutomationInvokePattern
    Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)

    If Err.Number = 0 Then
        On Error GoTo 0
        Exit Do
    Else
        Sleep 100
        count = count + 1
    End If
    On Error GoTo 0
Loop

InvokePattern.Invoke

Do
    Sleep 1000
    Completed = DownloadComplete()
    If Completed = "Yes" Then
        Exit Do
    Else
    End If
Loop

SendMessage h, WM_CLOSE, 0, 0

End Sub

但是,当我在家中运行此自动化程序时,有时在单击“保存”后会出现以下弹出窗口: DialogBox

如果弹出此按钮,我应该如何告诉VBA单击“重试”? 谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

由于这是第二个弹出通知栏,因此您无法调用代码中的AutomationElement Button,因为在IE中找不到“保存”按钮。

您需要将AutomationCodition iCnd重置为“重试”,并找到调用它的按钮。如果找不到保存按钮,则Button将是Nothing

While Not filefound
    If Dir(file_path) <> "" Then filefound = True
    Application.Wait (Now + TimeValue("0:00:01"))

    Dim o As IUIAutomation
    Dim e As IUIAutomationElement
    Set o = New CUIAutomation

    Dim h As Long
    h = ie.Hwnd
    h = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)

    If h <> 0 Then
        On Error Resume Next

        Set e = o.ElementFromHandle(ByVal h)
        Dim iCnd As IUIAutomationCondition
        Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Save")

        Dim Button As IUIAutomationElement
        Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
        If Button Is Nothing Then
            Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Retry")
            Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
        End If

        Dim InvokePattern As IUIAutomationInvokePattern
        Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
        InvokePattern.Invoke

        On Error GoTo 0
    End If
Wend