How to optimize excel VBA for clicking url - html

Run time error "70" while VBA is running.
Sometime the code runs smooth but sometime does not. Wondering if there is more reliable code for proceeding. It always stop in If link.innerHTML = "Balance Sheet" Then end if
Public Sub Get()
Dim ie As Object
Dim URL As String, link As Object, alllinks As Object
Dim eRowa As Long, eRowb As Long, eRowc As Long
Dim var As Object
Set var = ThisWorkbook.Worksheets("Sheet2").Cells(1, 1)
URL = "https://www.marketwatch.com/investing/stock/" & var & "/financials"
Set ie = CreateObject("internetexplorer.application")
With ie
.Visible = True
.navigate URL
While .Busy Or .readyState < 4: DoEvents: Wend
Set alllinks = ie.document.getElementsByTagName("a")
For Each link In alllinks
If link.innerHTML = "Balance Sheet" Then
link.Click
End If
Next link
While .Busy Or .readyState < 4: DoEvents: Wend
End With
Set ie = Nothing
End Sub
Expect smooth running without error 70

Use a timed loop to wait for presence of a tag. Use an attribute = value css selector with $ ends with operator for faster targeting of the appropriate element
Option Explicit
Public Sub GetInfo()
Dim ie As Object, url As String, link As Object
Dim var As Range, t As Date
Const MAX_WAIT_SEC As Long = 10
Set var = ThisWorkbook.Worksheets("Sheet2").Cells(1, 1)
url = "https://www.marketwatch.com/investing/stock/" & var.value & "/financials"
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.navigate2 url
While .Busy Or .readyState < 4: DoEvents: Wend
t = Timer
Do
On Error Resume Next
Set link = .document.querySelector("[href$='/balance-sheet']")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While link Is Nothing
If link Is Nothing Then Exit Sub
link.Click
While .Busy Or .readyState < 4: DoEvents: Wend
Stop '<== Delete me later
.Quit
End With
End Sub

Related

Excel VBA to activate selectitem in web and go web for data

I'm very fresh to excel VBA. I tried use all potential solutions in the internet for activate selectitem in web and get data table but it didn't work. My Excel VBA code and Javascript is below.
Sub GetQuarterFinancials()
Dim ie As Object, URL As String
URL = "https://www.marketwatch.com/investing/stock/aapl/financials"
Set ie = CreateObject("internetexplorer.application")
With ie
.Visible = True
.navigate URL
Do While .Busy
DoEvents
Loop
Do While .readyState <> 4
DoEvents
Loop
Set ticker = ie.document.getElementById("autocomplete_input")
ticker.value = "FB"
.document.getElementById("investing_ac_button").Click
Application.Wait (Now + TimeValue("00:00:05"))
Set selectitem = ie.document.getElementsByTagName("select")
For Each i In selectitem
i.value = "/investing/stock/msci/financials/income/quarter"
i.FireEvent ("onchange")
Next i
End With
End Sub
<select style="float:right" onchange="window.location = this.options[selectedIndex].value;">
<option value="/investing/stock/msci/financials" selected="selected">Annual Financials</option>
<option value="/investing/stock/msci/financials/income/quarter" >Quarter Financials</option>
</select>
<div style="clear:both"></div>
</div>
<div class="block">
<h2>Annual Financials for MSCI Inc.</h2>
You can use a css attribute = value selector to target the appropriate option from dropdown then select it.
Option Explicit
'VBE > Tools > References:
' Microsoft Internet Controls
Public Sub MakeSelections()
Dim ie As New InternetExplorer
With ie
.Visible = True
.Navigate2 "https://www.marketwatch.com/investing/stock/aapl/financials"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document
.querySelector("#autocomplete_input").Value = "FB" 'you could avoid search by adding ticker into url
.querySelector("#investing_ac_button").Click
End With
While .Busy Or .readyState < 4: DoEvents: Wend
Dim ele As Object
With .document
Do
On Error GoTo 0
Set ele = .querySelector("[value^='/investing/stock/fb/financials/income/quarter']")
On Error Resume Next
Loop While ele Is Nothing
.querySelector("[value^='/investing/stock/fb/financials/income/quarter']").Selected = True
.querySelector(".financials select").FireEvent "onchange"
Stop 'delete me later
End With
.Quit
End With
End Sub

Second drop down in HTML is not getting selected through VBA

My VBA code is not able to select the second drop down option once the first drop down is selected. Not sure why one dropdown is loading and second is not responding as per below code? Appreciate if you could help on fixing this. Regards
Dim IE As InternetExplorer
Dim HTMLDoc As HTMLDocument
Dim commodityStr As String
Dim commodityObj As HTMLObjectElement
Dim commodityCodes As IHTMLElementCollection
Dim codeCounter As Long
Dim EDateStr As String
Dim EDateObj As HTMLObjectElement
Dim EdateCodes As IHTMLElementCollection
Dim i As Integer
commodityStr = "MADHYA PRADESH"
EDateStr = "REWA"
Set IE = New InternetExplorer
With IE
.Visible = True
.navigate "http://hydro.imd.gov.in/hydrometweb/(S(ryta1dvaec5pg03bdnxa5545))/DistrictRaifall.aspx"
While .Busy Or .readyState <> READYSTATE_COMPLETE: Wend
Set HTMLDoc = IE.document
End With
Set commodityObj = HTMLDoc.getElementById("listItems")
For codeCounter = 0 To commodityObj.Length - 1
If commodityObj(codeCounter).innerText = commodityStr Then
commodityObj.Value = commodityObj(codeCounter).Value
commodityObj.Focus
commodityObj.FireEvent ("onchange")
While IE.Busy Or IE.readyState <> READYSTATE_COMPLETE: Wend
Exit For
End If
Next
Set EDateObj = HTMLDoc.getElementById("DistrictDropDownList")
For codeCounter = 0 To EDateObj.Length - 1
If EDateObj(codeCounter).innerText = EDateStr Then
EDateObj.Value = EDateObj(codeCounter).Value
While IE.Busy Or IE.readyState <> READYSTATE_COMPLETE: Wend
commodityObj.Focus
commodityObj.FireEvent ("onchange")
Exit For
End If
Next
You need a timed loop to allow for that execution of the onchange event. Also, you can make use of css attribute = value selectors to remove loops when targeting elements. It is likely the page does an XHR request so inspect via dev tools to see if that is the case.
Option Explicit
'VBE > Tools > References:
' Microsoft Internet Controls
Public Sub MakeSelections()
Dim ie As InternetExplorer, ele As Object, t As Date
Const MAX_WAIT_SEC As Long = 5
Dim commodity As String, iDate As String
commodity = "MADHYA PRADESH"
iDate = "REWA"
Set ie = New InternetExplorer
With ie
.Visible = True
.Navigate2 "http://hydro.imd.gov.in/hydrometweb/(S(3qitcijd521egpzhwqq3jk55))/DistrictRaifall.aspx"
While .Busy Or .readyState < 4: DoEvents: Wend
.document.querySelector("[value='" & commodity & "']").Selected = True
.document.querySelector("[name=listItems]").FireEvent "onchange"
t = Timer
Do
On Error Resume Next
Set ele = .document.querySelector("[value='" & iDate & "']")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While ele Is Nothing
If Not ele Is Nothing Then
ele.Selected = True
.document.querySelector("#GoBtn").Click
Else
Exit Sub
End If
Stop
.Quit
End With
End Sub

HTML object VBA

I need to enter to this button but I can't find the name, Id or anything which help me to identify the bottom.
This is the code in HTML.
Create Third Party Customer
What code can I use in VAB to connect with this button?
This is the code:
VBA:
Sub test()
Dim IE As New InternetExplorer, html As HTMLDocument
With IE
.Visible = True
.navigate "http://zvc-t-mdmap01:7507/utils/enterLogin.jsp"
Do Until .readyState = READYSTATE_COMPLETE: Loop
Set html = .document
End With
html.getElementById("username").Value = Sheets("InfoSphere").Range("i4")
html.getElementById("password").Value = Sheets("InfoSphere").Range("i5")
html.getElementById("company_code").Value = Sheets("InfoSphere").Range("i6")
html.getElementById("loginButton_label").Click
Application.Wait (Now + TimeValue("0:00:05"))
With IE
.Visible = True
.navigate "http://zvc-t-mdmap01:7507/worklist/worklistconsole.jsp?colAreaName=Third%20Party%20Customer%20Management%20Process"
Do Until .readyState = READYSTATE_COMPLETE: Loop
Set html = .document
End With
Set link = IE.document.getElementsByTagName("a")
For Each l In link
If l.innerText = "Create Third Party Customer" Then
l.Click
Exit For
End If
Next l
'Add
IE.document.querySelector("[stepname='Create Third Party Customer']").Click
End Sub
It didn't work but I don't receive an error either, this is the final code:
Sub test()
Dim IE As New InternetExplorer, html As HTMLDocument
Dim aTags As Object, aTag As Object
With IE
.Visible = True
.navigate "http://zvc-t-mdmap01:7507/utils/enterLogin.jsp"
Do Until .readyState = READYSTATE_COMPLETE: Loop
Set html = .document
html.getElementById("username").Value = Sheets("InfoSphere").Range("i4")
html.getElementById("password").Value = Sheets("InfoSphere").Range("i5")
html.getElementById("company_code").Value = Sheets("InfoSphere").Range("i6")
html.getElementById("loginButton_label").Click
Application.Wait (Now + TimeValue("0:00:05"))
.Visible = True
.navigate "http://zvc-t-mdmap01:7507/worklist/worklistconsole.jsp?colAreaName=Third%20Party%20Customer%20Management%20Process"
Do Until .readyState = READYSTATE_COMPLETE: Loop
Set html = .document
End With
'Add
Set aTags = html.getElementsByTagName("a")
For Each aTag In aTags
If InStr(aTag.outerHTML, "Create Third Party Customer") > 0 Then
aTag.Click
Exit For
End If
Next
End Sub
Try an attribute = value selector
ie.document.querySelector("[stepname='Create Third Party Customer']").click
Brute force approach:
Dim aTags As Object, aTag As Object
Set aTags = html.getElementsByTagName("a")
Dim event_onClick As Object
Set event_onClick = html.createEvent("HTMLEvents")
event_onClick.initEvent "click", True, False
For Each aTag In aTags
If InStr(aTag.outerHTML, "Create Third Party Customer") > 0 Then
With aTag
.Click
.dispatchEvent event_onClick
.FireEvent "onclick"
End With
Exit For
End If
Next

No error, but No Data resulting from VBA HTML Pull

EDITED: So this one works for me.. I am looking to convert this to my purposes now. I am trying to switch this to the title and price, but when I convert the line:
Set links = .document.querySelectorAll(".s-item__link[href]")
to
Set links = .document.querySelectorAll(".s-item__title [h3]")
It pulls "[object HTMLHeadingElement]" for each row - thoughts?
Option Explicit
Public Sub GetInfo()
Dim ie As New InternetExplorer, ws As Worksheet, t As Date
Const MAX_WAIT_SEC As Long = 10
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ie
.Visible = True
.Navigate2 "https://www.ebay.com/"
While .Busy Or .readyState < 4: DoEvents: Wend
ie.document.querySelector("#gh-ac").Value = "Bike"
ie.document.querySelector("#gh-btn").Click
While .Busy Or .readyState < 4: DoEvents: Wend
Dim links As Object, i As Long, count As Long
t = Timer
Do
On Error Resume Next
Set links = .document.querySelectorAll(".s-item__link[href]")
count = links.Length
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While count = 0
For i = 0 To links.Length - 1
ws.Cells(i + 1, 1) = links.item(i)
Next
.Quit
End With
End Sub
Here is an example of doing a search for Bike on ebay and looping until links are present
Option Explicit
Public Sub GetInfo()
Dim ie As New InternetExplorer, ws As Worksheet, t As Date
Const MAX_WAIT_SEC As Long = 10
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ie
.Visible = True
.Navigate2 "https://www.ebay.com/"
While .Busy Or .readyState < 4: DoEvents: Wend
ie.document.querySelector("#gh-ac").Value = "Bike"
ie.document.querySelector("#gh-btn").Click
While .Busy Or .readyState < 4: DoEvents: Wend
Dim links As Object, i As Long, count As Long
t = Timer
Do
On Error Resume Next
Set links = .document.querySelectorAll(".s-item__link[href]")
count = links.Length
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While count = 0
For i = 0 To links.Length - 1
ws.Cells(i + 1, 1) = links.item(i)
Next
.Quit
End With
End Sub

VBA Auto Login Web page and fetch the data

I am trying to login Web page and fetch data however my login details are not getting update, i have tried all possibilities code from your forum, nothing is working for me
Below is my code, am getting attached error
Sub test()
Dim ie As Object
Dim objCollection As Object
Dim i As Integer
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate "https://portal.expeditors.com/expo/login"
Do While ie.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
'Get all the elements with input tag name
Set objCollection = ie.document.getElementsByTagName("input")
i = 0
'Loop through all elements and find login form and fill it
While i < objCollection.Length
'Login name
If objCollection(i).Name = "username" Then
objCollection(i).Value = "bom-sumand"
End If
'Store login button in object
If objCollection(i).Type = "submit" Then
Set objElement = objCollection(i)
End If
i = i + 1
Wend
'Click login
objElement.Click
'Clean up
Set ie = Nothing
End Sub
I would use the available ids rather than looping to find the input boxes and sign in. These are much faster selector methods. You can add a .Focus. Also, swop InternetExplorer for InternetExplorerMeduim in some cases.
If problem continues check your internet settings in case site is blocked.
Open the URL via creating an IE instance direct.
Option Explicit
Public Sub Login()
Dim ie As New InternetExplorer 'InternetExplorerMedium
Const MAX_WAIT_SEC As Long = 5
Dim t As Date, ele As Object
With ie
.Visible = True
.navigate "https://portal.expeditors.com/expo/login"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document
Do
DoEvents
On Error Resume Next
Set ele = .getElementById("j_username")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While ele Is Nothing
If ele Is Nothing Then Exit Sub
With ele
.Focus
.Value = "bob"
End With
With .getElementById("j_password")
.Focus
.Value = "penny"
End With
.getElementById("signInBtn").Click
End With
While .Busy Or .readyState < 4: DoEvents: Wend
Stop '<== Delete me later
.Quit
End With
End Sub
Macro trying and failing to open a second instance of IE try this.
Sub test()
Dim ie As Object
Dim redURL As String
Dim objCollection As Object
Dim i As Integer
redURL = "https://portal.expeditors.com/expo/login"
On Error Resume Next
Set ie = GetObject(, "InternetExplorer.Application")
If Err Then
Set ie = CreateObject("InternetExplorer.Application")
End If
On Error GoTo 0
ie.Visible = True
ie.Navigate redURL
Do While ie.Busy
Loop
End Sub