VBA Internet Explorer Automation 'Permission Denied'

后端 未结 8 1308
别那么骄傲
别那么骄傲 2020-12-19 23:11
Dim IE as New InternetExplorer
IE.Visible = True

IE.Navigate(\"http://www.google.com\")

Do Until IE.Busy = False
Loop

IE.document.getElementsByTagName(\"Input\")(         


        
8条回答
  •  -上瘾入骨i
    2020-12-19 23:56

    This is a common issue with Internet Explorer automation in VBA. It generally seems to happen after a new page has been loaded. I have had success using a combination of DoEvents, Application.Wait, and setting my HTMLDocument object to Nothing after a new page load.

    I have posed sample code below to demonstrate:

    Option Explicit
    
    Sub IEAutomation()
    
        Dim IE As InternetExplorer
        Dim html As HTMLDocument
        Dim i As HTMLHtmlElement
        Dim search_bar_id As String
        Dim submit_button_name As String
        Dim search_term As String
    
        'Define Variables
        search_bar_id = "lst-ib"
        submit_button_name = "btnK"
        search_term = "Learning VBA"
    
        'Create IE and Naviagate to Google
        Set IE = CreateObject("InternetExplorer.Application") 'Late Binding
        IE.Visible = True
        IE.navigate "http://www.google.com"
    
        'Wait for IE To Load
        Do While IE.readyState <> READYSTATE_COMPLETE: DoEvents: Loop
    
        'Create HTMLDocument Object
        Set html = IE.document
    
        'Enter Search Term into Search Bar and Click Submit Button
        html.getElementById(search_bar_id).innerText = search_term
        Application.Wait Now + TimeValue("0:00:01")
        html.getElementsByName(submit_button_name)(, 1).Click
    
        'Wait for New Page to Load (** DoEvents Helps with the Permission Issue **)
        Do While IE.readyState <> READYSTATE_COMPLETE: DoEvents: Loop
    
        'After Page Loads, Reset HTMLDocument Object and Wait 1 Second Before Recreating It
        Set html = Nothing
        Application.Wait Now + TimeValue("0:00:01") '<<< This seems to really help
        Set html = IE.document
    
        'Print All Elements In H3 Tags to Immediate Window in VBE
        For Each i In html.getElementsByTagName("H3")
            Debug.Print i.innerText
        Next i
    
    End Sub
    

提交回复
热议问题