首页 > 解决方案 > VBA 从 IE 下载文件:单击“保存”后出现第二个弹出窗口

问题描述

我正在自动化一个过程,我必须从 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

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

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

标签: excelvba

解决方案


由于这是第二个弹出通知栏,因此您无法调用代码中的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

推荐阅读