I want my macro to open each link stored in a spreadsheet in a separate IE tab. I am successful with opening the first link, but for some reason on the second iteration of the loop I get:
Automation error.The interface is unknown
error.
I suspect the macro somehow loses IE object reference after first iteration, but I am not sure why.
Range is set OK.
Here is the code:
Sub OpenCodingForms()
Dim wb1 As Workbook
Dim ws1 As Worksheet
Dim CodingFormLinks As Range
Dim IE as InternetExplorerMedium
Set wb1 = Workbooks("New shortcut.xlsm")
Set ws1 = wb1.Worksheets("Data")
Set CodingFormLinks = ws1.Range("A2", Range("A2").End(xlDown))
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
ws1.Activate
For Each link In CodingFormLinks.Cells
IE.Navigate link, CLng(2049)
Next link
End Sub
I ran into this issue before and ended up just writing a routine to get the instance. You will need to add a reference to shell controls and automation.
you may have to adjust this to look for the sURL var in the beginning of the actual URL if there is redirection.
Sub OpenCodingForms()
Dim wb1 As Workbook
Dim ws1 As Worksheet
Dim CodingFormLinks As Range
Dim IE As InternetExplorerMedium
Set wb1 = Workbooks("New shortcut.xlsm")
Set ws1 = wb1.Worksheets("Data")
Set CodingFormLinks = ws1.Range("A2", Range("A2").End(xlDown))
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
ws1.Activate
Dim sUrl As String
For Each link In CodingFormLinks.Cells
sUrl = link.Value
IE.navigate sUrl, CLng(2048)
Set IE = GetWebPage(sUrl)
Next link
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Desc: The Function gets the Internet Explorer window that has the current
' URL from the sURL Parameter. The Function Timesout after 30 seconds
'Input parameters:
'String sURL - The URL to look for
'Output parameters:
'InternetExplorer ie - the Internet Explorer window holding the webpage
'Result: returns the Internet Explorer window holding the webpage
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetWebPage(sUrl As String) As InternetExplorer
Dim winShell As Shell
Dim dt As Date
'set the timeout period
dt = DateAdd("s", 300, DateTime.Now)
Dim IE As InternetExplorer
'loop until we timeout
Do While dt > DateTime.Now
Set winShell = New Shell
'loop through the windows and check the internet explorer windows
For Each IE In winShell.Windows
'check for the url
If IE.LocationURL = sUrl Then
'set the window visible
IE.Visible = True
IE.Silent = True
'set the return value
Set GetWebPage = IE
Do While IE.Busy
DoEvents
Loop
Set winShell = Nothing
Exit Do
End If
Next IE
Set winShell = Nothing
DoEvents
Loop
End Function
Related
I wrote some code to scrape data from a website. I've tested it on 5 difference machines with different versions of excel and it all works fine. But on the intended users machine we get type mismatch error.The code fails at the last line below.
Sub LogIn()
Dim ie As SHDocVw.InternetExplorer
Dim iDoc As MSHTML.HTMLDocument
Dim ele As MSHTML.IHTMLElement
Dim eles As MSHTML.IHTMLElementCollection
Dim tableSection As MSHTML.IHTMLElement
Dim tableRow As MSHTML.IHTMLElement
Dim tableCell As MSHTML.IHTMLElement
Dim smallCell As MSHTML.IHTMLElement
Dim iCol As Integer
Dim iRow As Integer
Dim iCounter As Integer
iRow = 0
Do
iRow = iRow + 1
Loop Until Cells(iRow, 5) = ""
Range(Cells(1, 5), Cells(iRow, 6)).ClearContents
Set ie = New InternetExplorer
ie.Visible = False
ie.navigate ("https://www.howdidido.com/")
Do While ie.readyState <> READYSTATE_COMPLETE
Loop
Set iDoc = ie.document
any help greatly appreciated.
I have tried the following code and it is working alright. Maybe it can help you (seems as two loops and doEvents are needed for the ready state completes).
Dim iDoc As MSHTML.HTMLDocument
Dim iCol As Integer
Dim iRow As Integer
Dim iCounter As Integer
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
Set IE = CreateObject("InternetExplorer.Application")
'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True
'Define URL
URL = "https://www.automateexcel.com/excel/"
'Navigate to URL
IE.Navigate URL
' Statusbar let's user know website is loading
Application.StatusBar = URL & " is loading. Please wait..."
' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
'Webpage Loaded
Application.StatusBar = URL & " Loaded"
Set iDoc = IE.Document
'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
When I launch the site via my code, there is an error of type "method document of object iwebbrowser2 failed " at the level of my variable "oDoc"
Private Function CreerNavigateur(ByVal mails As String)
Dim IE As Object
Dim oDoc As Object
Dim Htable, maTable As Object
Dim text As String
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = False
IE.navigate "https://csrtool-ssl.sso.infra.ftgroup/csrtool_web/Bricks/pg/osuit/pages/identity/IdentityAccountAndUsers?type=emailAlias&value=" & mails & "&tab_main=AccountInfo"
While IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE: DoEvents: Wend
Set oDoc = IE.Document
Set Htable = oDoc.getElementsByTagName("div")(1)
' MsgBox Htable.innerhtml
Set maTable = Htable.getElementsByTagName("span")
'MsgBox maTable(0).href
'myData = maTable(0).innertext
'MsgBox (myData)
IE.Quit
'On libère les variables
Set IE = Nothing
Set oDoc = Nothing
End Function
thank you for helping me to see my mistake
One of the possible reasons of such errors are security restricitions. Try to add infra.ftgroup to Trusted sites zone in IE settings:
Also try to open the website in compatibility view:
And play a bit with modes on Developer tools F12 - Emulation tab:
I'm using Excel VBA to log into a website, then type a .txt file name in a search box and click a button/link to search for it in the resulting second page. The resulting third page has an icon you have to click to download the file. Lastly I want to input the info in the .txt file to a new excel spreadsheet.
My getLogin function works and I successfully log into the website. Stepping through with F8 I can see each line of code entering in my username and password values in the respective fields. I'm on the second page level where I want to search in a searchbox using a filename, but at
If Not FileN Is Nothing And FileN.Length > 0 Then
FileN(0).Value = fileName
in the SearchFile function, when I step through it using F8, I see it keeps skipping FileN(0).Value = fileName and doesn't input the file name. The same happens for the link I click to search,
Set ElementCol = ie.document.getElementsByTagName("a")
For Each l In ElementCol
If l.href = "javascript:myFunction('/mailbox/jsp/MBIList.jsp')" Then
l.Click
It doesn't enter the If Statement and therefore doesn't click it.
My code so far:
Sub getComponents()
Dim WebAddressIn As String
Dim ie As Object
WebAddressIn = "https://..."
'get ie instance to work with that is logged in
Set ie = getLogin(WebAddressIn, "usern", "pw")
Do Until ie.readyState = 4
Loop
ie.Visible = True
Dim fileName As String
fileName = Format(Now(), "yyyyMMdd") & ".TXT"
Set ie = searchFile(fileName, ie)
End Sub
Function searchFile(fileName As String, ie As Object)
Dim Doc As Object, lastRow As Long, tblTR As Object
Dim UserString As String
Dim FileN As Object ' MSHTML.IHTMLElement
Dim ElementCol As Object ' MSHTML.IHTMLElementCollection
Dim AllText As String
Do While ie.Busy
Loop
Set FileN = ie.document.getElementsByName("MsgNamePattern")
If Not FileN Is Nothing And FileN.Length > 0 Then
FileN(0).Value = fileName
End If
Do While ie.Busy
Loop
Set ElementCol = ie.document.getElementsByTagName("a")
For Each l In ElementCol
If l.href = "javascript:myFunction('/mailbox/jsp/MBIList.jsp')" Then
l.Click
Exit For
End If
Next l
Do While ie.Busy
Loop
Set searchFile = ie
Set ie = Nothing
End Function
Function getLogin(WebAddressIn As String, UserNameIn As String, PasswordIn As String)
Dim Doc As Object, lastRow As Long, tblTR As Object
Set ie = CreateObject("internetexplorer.application")
ie.Visible = False
Dim UserString As String
Dim PWString As String
ie.Navigate2 WebAddressIn
ie.Visible = True
Dim UserN As Object ' MSHTML.IHTMLElement
Dim PW As Object ' MSHTML.IHTMLElement
Dim ElementCol As Object ' MSHTML.IHTMLElementCollection
Dim AllText As String
Do While ie.Busy
Loop
' enter username and password in textboxes
Set UserN = ie.document.getElementsByName("userid")
If Not UserN Is Nothing And UserN.Length > 0 Then
' fill in first element named "username", assumed to be the login name field
UserN(0).Value = UserNameIn
End If
Set PW = ie.document.getElementsByName("password")
' password
If Not PW Is Nothing And PW.Length > 0 Then
' fill in first element named "password", assumed to be the password field
PW(0).Value = PasswordIn
End If
Do While ie.Busy
Loop
'Clicks the Sign in button
Set ElementCol = ie.document.getElementsByName("submit")
For Each btnInput In ElementCol
If btnInput.Value = "*Sign In" Then
btnInput.Click
Exit For
End If
Next btnInput
Do While ie.Busy
Loop
Set getLogin = ie
Set ie = Nothing
End Function
And here's the relevant HTML code on this second resulting page:
The Search Box -
<input type="text" name="MsgNamePattern" size="20" onblur="validateMessageName(this)">
The link to search -
<td align="center" valign="center"> <img border="0" src="/mailbox/images/go_off.gif" vspace="7" name="Go" align="top">
</td>
The code works correctly but when I try to close IE I get the following error:
"Run Time Error 91"
Dim IE As Object
Dim shellWins As New ShellWindows
Dim IE_URL As String
Dim Row As Integer
Row = 2
For Each IE In shellWins
IE_URL = IE.LocationURL
If IE_URL <> vbNullString Then
Sheet1.Range("A" & Row) = IE_URL
row = Row + 1
End If
Next
Set shellWins = Nothing
Set IE = Nothing
IE.quit
NEW CODE:
Dim shellWins As New ShellWindows
Dim objIE As Object
Dim objIE_TabURL As String
Dim Rowcount As Long
Rowcount = 2
With objIE
Set objIE = CreateObject("InternetExplorer.Application")
For Each objIE In shellWins
objIE_TabURL = objIE.LocationURL
If objIE_TabURL <> vbNullString And InStr(objIE_TabURL,
"file://") = 0 Then
Rowcount = Rowcount + 1
sht2.Range("A" & Rowcount) = objIE_TabURL
End If
Next
objIE.Quit
End With
END NEW CODE
I try to read the url from tabs open in a IE session to export it in a sheet.
I'm so sorry but i'm a newbie in a VBA :-(
IE isn't actually set to an instance of Internet Explorer at any point, you're using it as an object variant in a loop. Once the loop finishes, the variables becomes out of scope, and therefore cannot be accessed any more in the way you would like.
If you want to close IE after retrieving the URL, change your code to:
For Each IE In shellWins
IE_URL = IE.LocationURL
If IE_URL <> vbNullString Then
Sheet1.Range("A" & Row) = IE_URL
row = Row + 1
IE.Quit '// Close IE here, while the variable is still in scope
End If
Next
Note there is no need to Set IE = Nothing at the end of your routine as VBA automatically manages memory for you.
I am fairly new to VBA and VBA in excel, I have been trying to find out how to conditionally scrape web data based off of one cells value ("Guid") and have not really found a way to progress the function -- to make it dynamic. As of right now I can only get it to retrieve data for one specific cell, and print in another specified cell. I believe I am just missing some kind of looping variable function? (aside from there is probably a more correct way of writing the code).
Sub ie_open()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Dim Guid As Range
Dim ie As Object
Dim URL As String
URL = "https://url.com/userpage="
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Detail Report - Individuals")
Set Guid = ws.Range("E2")
Set TxtRng = ws.Range("F2")
Set ie = CreateObject("INTERNETEXPLORER.APPLICATION")
ie.NAVIGATE (URL + Guid)
ie.Visible = True
While ie.ReadyState <> 4
DoEvents
Wend
TxtRng = ie.document.getelementbyid("lbl_Location").innertext
End Sub
Thank you in advance.
Turn on a reference to HTML elements (Go to Tools -- References. You should also turn on a reference to Microsoft Internet controls so you can declare IE as an InternetExplorer object rather than just an object, but it's not necessary), then you can loop through each element like
Sub ie_open()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Dim Guid As Range
Dim ie As Object
Dim URL As String
'ADDED THIS
Dim sl as Ihtmlelement
Dim r as long = 1
URL = "https://url.com/userpage="
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Detail Report - Individuals")
Set Guid = ws.Range("E2")
Set TxtRng = ws.Range("F2")
Set ie = CreateObject("INTERNETEXPLORER.APPLICATION")
ie.NAVIGATE (URL + Guid)
ie.Visible = True
While ie.ReadyState <> 4
DoEvents
Wend
For each sl in ie.document.all
ws.cells(r, 1).value = sl.innertext
r = r + 1
Next
'TxtRng = ie.document.getelementbyid("lbl_Location").innertext
End Sub
Edit: forgot to increment the r variable in the loop, and I think it should be IE.Document.All instead of just IE.Document when initializing the loop