VBA random automation error in CreateObject("InternetExplorer.Application") - vba

So...
I searched through the forum, and really found a lot of threads with awesome suggestions, but none of them works (Example
Thing is my code randomly breaks on Set ie = CreateObject("InternetExplorer.Application"). After resuming code it is always continuing without a problem. Error msg is:
Run-time error '-2147467259 (80004005)' Automation error Unspecified error
After each iteration I do ie.quit and set ie = nothing and additionally I checked and clear processes, just in case if internetexplorer would pile up and suffocate my computer in the background.
Something like:
If CheckIFRunning("INTERNET EXPLORER.EXE") = True Or CheckIFRunning("IEXPLORE.EXE") = True Then oProc.Terminate
And like many suggested I tried Set ie = New InternetExplorerMedium but with no luck.
I added application.wait as I thought maybe there is a split second where IE is still not close and I'm already starting a new instance but that didn't help as well.
I can add a code, but it is extremely long and my only problem is on CreateObject.
I would like to at least resume execution even if for some reason really there is a problem with creating object (and yes, I've tried on error resume next).

Try this, hope it will help you .
replace
Set ie = CreateObject("InternetExplorer.Application")
with
' Ignore the error
On Error Resume Next
' if IE already open then try to get the object
Set ie = GetObject(, "InternetExplorer.Application")
' Check is there error after the get object
If Err.Number <> 0 Then
' if an error happen then try to create new IE
Err.Clear
Set ie = CreateObject("InternetExplorer.Application")
End If
' Turn Error reporting back on
On Error GoTo 0

Related

VBA Auotmation - Closing IE Before IE.Quit Runs Freezes Excel

I have some code which closes IE after some VBA Website Automation (after waiting for a period of time).
Application.Wait (Now + TimeValue("00:00:55"))
IE.Quit
Set IE = Nothing
Set doc = Nothing
The problem is that if someone inadvertently closes IE before the IE.Quit code executes, Excel freezes because the IE property no longer exists.
I've tried something like this (please see below code excerpt) but Excel still freezes if it's closed before the timer executes the code (Run-Time error '462', The remote server machine does not exist or is unavailable):
Application.Wait (Now + TimeValue("00:00:55"))
If IE Is Nothing Then
'do nothing
Else
IE.Quit
Set IE = Nothing
Set doc = Nothing
End If
Any ideas or guidance would be much appreciated.
I'm agree with what Mathieu says. The freeze is due to the waiting is still being executed. Everything you put after Application.Wait will be executed after the waiting--which is to say after "the freeze".
You can only add On Error Resume Next after Application.Wait (Now + TimeValue("00:00:55")) to avoid the error display, but you can't stop the waiting.

Cant download a scorecard from pgatour.com

I've searched throughout the site here to improve my simple code, but continue to have an error 424 at the set allRowofdata line, which I gleaned from here. I'm just trying to load a golfers scorecard into my excel spread. I appreciate any help I can get.
Here's my code:
Note: based on advise from below, I've changed my code to the below, but now get a type mismatch error at set allRowOfData.
Sub Trial()
Dim IE As InternetExplorer
Dim allRowOfData
Dim document As Object
Set IE = New InternetExplorer
IE.Visible = False
IE.navigate "https://www.pgatour.com/players/player.32757.patton-kizzire.html/scorecards/r457"
Do Until IE.readyState = 4: DoEvents: Loop
Set allRowOfData = IE.document.getElementById("module-1510443455695-953403-17")
Dim myValue As String: myValue = allRowOfData.Cells().innerHTML
IE.Quit
Set IE = Nothing
Range("A1").Value = myValue
End Sub
I think you've set the page element before it gets a chance to load on the page, therefore 'allRowOfData' remains nothing.
Consider replacing this:
Application.Wait Now + TimeSerial(0, 0, 1)
With:
Do Until IE.ReadyState = 4: DoEvents: Loop
Or alternatively (inefficient but can't see any reason why it wouldn't work):
Do until not(allRowOfData is nothing)
Do events
Set allRowOfData = IE.document.getElementById("#module-1510443455695-953403-17")
Loop
The above assumes your usage of .getElementByID method is correct. Untested, written on mobile.
Edit 1:
See if changing this
Dim allRowOfData
To this
Dim allRowOfData As IHTMLElement
Works.
Before you re-run code, in VBA editor, click Tools > References and add a reference to the Microsoft HTML Object Library (scroll down and tick it).
Type Mismatch would suggest we're assigning something to a variable of the wrong type, so let's get rid of the implicit variant.
I haven't been able to examine the code's HTML source as I'm on mobile. It may be the case though that the specific element that you want is created subsequent to the page's initial loading (in which case you may need to use the inefficient alternative above), or that you need to iterate through a IHTMLElementCollection to get at the information. All depends on the page's structure and loading behaviour.

My excel macro generates errors inconsistently

I am working on a macro to automate some web browser stuff and there is an intermittent runtime error 91 "object variable or with block variable not set". I have been playing around with how I declare and create my browser object but nothing is working.
Sub Morning_Script()
Dim WebBrowser As Object
Set WebBrowser = New InternetExplorerMedium
WebBrowser.Visible = True
WebBrowser.navigate "www.google.com"
While WebBrowser.Busy = True
DoEvents
Wend
WebBrowser.document.getElementById("lst-ib").Value = "test"
'WebBrowser.document.getElementById("verify").Value = Worksheets("Sheet1").Range("B2")
'WebBrowser.document.getElementById("institution").Value = "xxx"
'Worksheets("Sheet1").Range("B1").Clear
'Worksheets("Sheet1").Range("B2").Clear
End Sub
The URL has been changed to a public website and the form entry has been commented out for now.
If you would prefer to avoid fixed timers, try this one:
Dim objElement As Object: Set objElement = Nothing
While objElement Is Nothing
Set objElement = WebBrowser.document.getElementById("lst-ib")
DoEvents
Wend
objElement.Value = "test"
If you would like to refer to verify and institution to, you would have to implement this scheme for them, too and wait until all three variables are non-nothing. You may also want to set a timeout or maximum retry number if there is a really great number of pages to download.

Object Required Error on VBA (submitting IE form using VBA)

My code was working perfectly fine a few hours ago. But when I open the document now and run it, I get the error:
Run-time error '424': Object required
Here's my code:
Dim ieApp As New SHDocVw.InternetExplorer
ieApp.Visible = True
ieApp.Navigate = "<url here; sorry, its confidential>"
Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
Dim ieElement As Object
Set ieElement = ieApp.Document.getElementById("i_specialist")
ieElement.Value = "TestValue"
The error points to:
Set ieElement = ieApp.Document.getElementById("i_specialist")
I really have no idea what went wrong. I'm thinking two possible causes:
- Object type is wrong
- Something went wrong with loading the page that the code can't find the field
Any help is appreciated! Thanks!
did you checked in the html document page that an html element with the id i_specialist is exist?
anyway when im working with htmlElements im doing it like this.. worth to give it a try...
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Do Until .ReadyState = 4
DoEvents
Loop
.document.all.Item("i_specialist").Value = "TestValue"
End With

Detect if an object has been disconnected from its clients

I am having an issue with automating an Excel file. The VBA script within Excel first opens a Word application and Word document:
Dim wordApp As Object
Set wordApp = CreateObject("Word.Application")
vPath = Application.ActiveWorkbook.Path
Set wordDoc = wordApp.Documents.Open(vPath & "\test.doc")
And then I call a subroutine within the Word document passing some data from the Excel file:
Call wordApp.Run("StartWithData", variable1, variable2)
If Excel detects that an error occurs in that subroutine, I close the Word document and Word application from Excel in a label I call Err1:
On Error Goto Err1
'all the code from above
Exit Sub
Err1:
wordDoc.Close wdCloseWithoutSaving
wordApp.Quit SaveChanges:=wdDoNotSaveChanges
Set wordDoc = Nothing
Set wordApp = Nothing
This works perfectly fine under normal circumstances; however, if the Word document or application are closed before the Err1 label executes (such as the user manually closing the document), I get the following error:
Run-time error '-2147417848 (80010108)':
Automation error The object invoked has disconnected from its clients.
which makes perfect sense because the wordApp and/or wordDoc variables still reference the Application and Document objects and those objects do not exist anymore (yet are also not considered to be Nothing).
So here is my inquiry: Is there a way to check if an object has been disconnected from its client before the run-time error occurs so as to avoid having to rely on on error resume next?
Such as:
If Not isDisconnected(wordDoc) Then
wordDoc.Close wdCloseWithoutSaving
End If
If Not isDisconnected(wordApp) Then
wordApp.Quit SaveChanges:=wdDoNotSaveChanges
End If
Update 1:
After looking at omegastripes' answer, I realized that the error given above only occurs when the document (wordDoc) was the object that got disconnected. If the Word application (wordApp) is what got disconnected, I get the following error:
Run-time error '462':
The remote server machine does not exist or is unavailable
Consider the below example:
Sub Test()
Dim wordApp As Object
Dim wordWnd As Object
Dim wordDoc As Object
Set wordApp = CreateObject("Word.Application")
Set wordWnd = wordApp.Windows ' choose any object property as indicator
wordApp.Visible = True ' debug
Set wordDoc = wordApp.Documents.Open(Application.ActiveWorkbook.Path & "\test.doc")
MsgBox IsObjectDisconnected(wordWnd) ' False with opened document
wordDoc.Close
MsgBox IsObjectDisconnected(wordWnd) ' False with closed document
wordApp.Quit ' disconnection
MsgBox IsObjectDisconnected(wordWnd) ' True with quited application
End Sub
Function IsObjectDisconnected(objSample As Object) As Boolean
On Error Resume Next
Do
IsObjectDisconnected = TypeName(objSample) = "Object"
If Err = 0 Then Exit Function
DoEvents
Err.Clear
Loop
End Function
Seems any type detection of the variable, which references to the intrinsic Word objects, like .Documents, .Windows, .RecentFiles, etc., made immediately after document close or application quit commands have been invoked, may throw the error 14: Out of string space, while Word application processing the command. The same detection on the Applicationobject , may also hang Excel application.
In the example TypeName() call is wrapped into OERN loop, that should skip irrelevant results to get explicit disconnection feedback, relying on the type name, but not on the error number. To avoid hanging, .Windows property is being checked instead of Application.