Не могу установить Internet Explorer 11, чтобы получить фокус - PullRequest
0 голосов
/ 06 мая 2019

У меня проблемы с сохранением загруженного файла в IE11 с помощью макроса MS ACCESS.

Здесь я хочу щелкнуть после того, как я был на ссылке для скачивания:

enter image description here

Мне нужно войти в систему с именем пользователя / паролем, чтобы попасть на эту страницу.

В настоящее время я использую SendKeys для получения файла, и когда я выполняю свой макрос вручную, он отлично работает. Однако, когда я запускаю свой макрос с запланированной задачей Windows, Internet Explorer теряет фокус, и клавиши sendkeys выполняются на рабочем столе.

Я пробовал несколько вещей, в том числе:

-IE.Visible = true

-Запустить sendkeys с объектом Shell

- попробовал Automation, но я не могу заставить его работать (я больше не использую "sendkeys" с этим методом). Я видел, что было несколько тем о переполнении стека, которые могли бы помочь мне, но мне не удалось заставить их работать: Управление IE11 кнопками диалогового окна «Хотите открыть / сохранить» в VBA или Панель уведомлений IE11 Frame Кнопка сохранения

- попытался скачать по ссылке, но не может заставить его работать

Вот мой код, я скрыл важные поля. Прошу прощения за французское в комментариях

Option Explicit
'Déclaration pour Sleep
#If VBA7 Then
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
#End If
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long

Public Function Fct_Elemica()

        Dim IEObject                        As InternetExplorer  'Objet Internet Explorer
        Dim IEDoc                           As HTMLDocument      'Document HTML
        Dim Shell                           As Object  'Objet WSScript

        'Automations
        Dim o                               As IUIAutomation
        Dim e                               As IUIAutomationElement
        Dim iCnd                            As IUIAutomationCondition
        Dim Button                          As IUIAutomationElement
        Dim InvokePattern                   As IUIAutomationInvokePattern

        'Phase de login
        Dim InputLogin                      As HTMLInputElement  'Element HTML pour le controle du champ login
        Dim InputPassword                   As HTMLInputElement  'Element HTML pour le controle du champ password
        Dim SubmitButton                    As HTMLInputElement  'Element HTML pour le controle des boutons d'envoi de formulaire

        'Phase de generation du report
        Dim ProductSelection                As HTMLSelectElement 'Element HTML pour le controle du champ type de produit
        Dim DateEndSelection                As HTMLInputElement  'Element HTML pour le controle du champ date de fin

        'Phase de telechargement du lien
        Dim ObjLink                         As Object            'Element HTML pour le controle des liens href
        Dim strDownloadLink                 As String            'URL du fichier a telecharger

        'Variables parametrables
        Dim strDownloadFolder               As String
        Dim strLoginPageURL                 As String
        Dim strLogin                        As String
        Dim strPassword                     As String

        Dim HWNDSrc                         As Long
        Dim h                               As LongPtr
        Dim Child                           As LongPtr




        strDownloadFolder = Nz(DLookup("PAR_TXT_VAL", "tParam", "PAR_LIB = 'DOWNLOAD_PATH'"), "") 'Get the download path
        strLoginPageURL = "https://portal.elemica.com/jsp/index.jsp"                              'Get the link of the website
        strLogin = "**************"                                                               'Login
        strPassword = "***********"                                                               'Password


        'Instanciation de la varirable IE
        Set IEObject = CreateObject("InternetExplorer.Application")

        'Affichage de la fenetre IE
        IEObject.Visible = True



        'Chargement de la page de login du site elemica
        IEObject.Navigate strLoginPageURL

        'On attend le chargement complet de la page
        IE_LOADING_WAIT IEObject

        'On pointe la page courante
        Set IEDoc = IEObject.Document


        'On pointe nos differents controleurs
        Set InputLogin = IEDoc.all("username_id")
        Set InputPassword = IEDoc.all("passwordID")
        Set SubmitButton = IEDoc.all("submitbutton")

        'On definit le texte que l'on souhaite placer a l'interieur et on se loggue
        InputLogin.value = strLogin
        InputPassword.value = strPassword
        SubmitButton.Click

        'Chargement de la page Expeditions -> Tous
        IEObject.Navigate "https://portal.elemica.com/nav?cmd=SRAll&reset=1&groupSelected=-1"

        'On attend le chargement complet de la page
        IE_LOADING_WAIT IEObject

        'On repointe la page courante
        Set IEDoc = IEObject.Document

        'On entre les valeurs pour parametrer la sortie de l'extraction
        Set ProductSelection = IEDoc.getElementsByName("productGroupIDSelected")(0)
        Set DateEndSelection = IEDoc.getElementsByName("toDate")(0)
        Set SubmitButton = IEDoc.getElementsByName("btnView")(0)

        ProductSelection.value = "105"
        DateEndSelection.value = Format(Now() + 3, "dd/mm/yyyy")
        SubmitButton.Click


        'On attend le chargement complet de la page
        IE_LOADING_WAIT IEObject

        'On interrompt de rafraichissement dynamique
        IEObject.Stop

        'On recherche le l'adresse du lien "Telecharger dans Excel"
        For Each ObjLink In IEDoc.Links
            If ObjLink.innerText = "Télécharger dans Excel" Then
                strDownloadLink = ObjLink.href
            End If
        Next ObjLink

        'Navigate to the download link
        IEObject.Navigate strDownloadLink

        'Wait until the page is completely loaded
        IE_LOADING_WAIT IEObject

'        Set o = New CUIAutomation
'        h = IEObject.hWnd
'        Sleep 500
'        Child = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)
'        Set e = o.ElementFromHandle(ByVal h)
'
'        Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "&Apri")
'
'        Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
'        Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
'        InvokePattern.Invoke

        Sleep 500
        SendKeys "^j"
        Sleep 500
        SendKeys "{RIGHT}"
        Sleep 500
        SendKeys "{RIGHT}"
        Sleep 500
        SendKeys "{RIGHT}"
        Sleep 500
        SendKeys "~"
        Sleep 500

        'Wait until the end of the download
        Sleep 20000

        'Close IE
        IEObject.Quit
        Shell ("taskkill /F /IM iexplore.exe")


        'Close vars
        Set InputLogin = Nothing
        Set InputPassword = Nothing
        Set SubmitButton = Nothing
        Set ProductSelection = Nothing
        Set DateEndSelection = Nothing
        Set IEDoc = Nothing
        Set IEObject = Nothing
        Set Shell = Nothing

End Function


Public Function IE_LOADING_WAIT(IEObject As InternetExplorer)

    'On boucle tant que la page n'est pas totalement chargee
    Do Until IEObject.ReadyState = READYSTATE_COMPLETE
        DoEvents
    Loop

End Function

Заранее спасибо за ответы, хорошего дня!

1 Ответ

1 голос
/ 06 мая 2019

Вы можете попытаться сослаться на шаги и пример кода ниже и попытаться изменить свой код, чтобы помочь решить проблему.

Копировать файл C: \ Windows \ System32 \ UIAutomationCore.dll файл для пользователей Documents, т.е. C: \ Users \ admin \ Documents , затем добавьте ссылку UIAutomationClient в ваш файл макроса.

Вставьте следующий код в ваш модуль:

    Option Explicit
    Dim ie As InternetExplorer
    Dim h As LongPtr
    Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr

Sub Download()
    Dim o As IUIAutomation
    Dim e As IUIAutomationElement
    Set o = New CUIAutomation
    h = ie.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, "Save")

    Dim Button As IUIAutomationElement
    Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
    Dim InvokePattern As IUIAutomationInvokePattern
    Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
    InvokePattern.Invoke
End Sub   

Ссылка:

Автоматизировать диалог сохранения для IE9 (vba)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...