简体   繁体   中英

vba internet explorer delete object

I'm making simple vba script witch is gonna open IE, get some informations and exit. Script open IE 35 times without problem, but after that it, works, but doesn't open IE anymore.

Sub Test()
for x=1 to 50
    Dim objIE As Object
    Set objIE = New InternetExplorer
    Set objIE = New InternetExplorerMedium
    objIE.Visible = True
    objIE.Navigate2 "http://www.google.com"
    objIE.Visible = False
    Set objIE = Nothing
next x
End Sub

I don't really get what you want do with your code, but here some tips that might help to fix the issue:

  1. You can take both the declaration and the set of your browser out of the loop, you don't need to declare it and set it each time:

     Dim objIE As Object Set objIE = New InternetExplorerMedium 
  2. Why are you setting objIE as New InternetExplorer , if you're right after setting it again as New InternetExplorerMedium ? That action is useless.

  3. Between the objIE.Navigate2 "http://www.google.com" and the Set objIE = Nothing you should probably wait some time, at least with a Do While objIE.busy Loop , because you don't even give the browser the time to load the document and you already destroy it.

  4. The Set objIE = Nothing can also be put out of the loop, you can re-use the same browser to navigate as many links as you want. Also, don't forget to quit it first before destroying it from memory with objIE.quit

If it works 35 times and keep on "working but doing nothing" starting from the 36th, wonder about the links are corrupted when you get there. You can check that with a Debug.Print on the link you're going to navigate each time.

This is the basic structure to automate IE with VBA.

Option Explicit

Sub PAO()

    Dim IE As InternetExplorer
    Dim url As String
    Const url$ = "http://www.google.com"

    Set IE = CreateObject("internetexplorer.application")

    IE.Visible = True
    IE.navigate url

    Set IE = Nothing

End Sub

Also, here is a Wait function that can help you to wait for the webpage to load.

Function IEWait(t As Long)

    Do While IE.Busy
        Application.Wait DateAdd("s", t, Now)
    Loop

End Function

This is how you use the function:

IEWait (1)
Do Until IE.readyState = READYSTATE_COMPLETE: DoEvents: Loop

Hope this will help you but let me know if you have any question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM