How do we select dropdown option using VBA?
For example, my HTML source code looks like below, and I try to select second one, "코스피200 선물".
<select name="isu_cd" id="isu_cdc74d97b01eae257e44aa9d5bade97baf">
<option value="ALL">전체</option>
<option value="KRDRVFUK2I">코스피200 선물</option>
....
</select>
Therefore, I try to iterate them using "For Each" after selecting that has name="isu_cd".
But the test for "MsgBox (botton.innnerHTML)" in the "For Each" gives me full of HTML code includes every other options as unexpected.
Could we iterate this with my approach?
Sub test_javascript()
url = "http://marketdata.krx.co.kr/mdi#document=060101"
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate url
Do Until (ie.readyState = 4 And Not ie.Busy)
DoEvents
Loop
Application.Wait (Now + TimeValue("00:00:10"))
Set Buttons = ie.document.getElementsByName("isu_cd")
For Each botton In Buttons
MsgBox (botton.innerHTML) 'it gives all of HTML code unexpectedly
If botton.innerHTML = "코스피200 선물" Then 'Nothing comes to here
MsgBox (botton.innerHTML)
botton.FireEvent ("onchange")
Exit For
End If
Next
End Sub
The problem is solved!
Buttons(0).Value = "KRDRVFUK2I" changes the dropdown box into what I desired.
The full solution is in below.
Sub test_javascript()
url = "http://marketdata.krx.co.kr/mdi#document=060101"
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate url
Do Until (ie.readyState = 4 And Not ie.Busy)
DoEvents
Loop
Application.Wait (Now + TimeValue("00:00:05"))
Set Buttons = ie.document.getElementsByName("isu_cd")
Buttons(0).Value = "KRDRVFUK2I"
Set goandfind = ie.document.getElementsByClassName("btn-board btn-board-search")(0)
goandfind.Click
Do Until (ie.readyState = 4 And Not ie.Busy)
DoEvents
Loop
Application.Wait (Now + TimeValue("00:00:05"))
Set buttons_excel = ie.document.getElementsByTagName("button")
For Each botton In buttons_excel
If botton.innerHTML = "Excel" Then
MsgBox (botton.outerHTML)
botton.FireEvent ("onclick")
Exit For
End If
Next
' do whatever
End Sub
Related
I'm trying to create a macro that will perform certain tasks on a webpage. What I'm struggling with is to select an option from a dropdown list.
This is (part of) my VBA Code:
Sub stackoverflow()
' ***** Dims for VBA *****
Dim objIE As SHDocVw.InternetExplorer
Dim ieDoc As MSHTML.HTMLDocument
Dim testURL As String
' ***** END *****
' ***** Dim Buttons*****
Dim StatusFld As MSHTML.HTMLInputElement
' ***** END *****
testURL = "https://test.com"
'Create Internet Explorer Object
Set objIE = New SHDocVw.InternetExplorer
'Navigate to URL
objIE.navigate testURL
'Wait until page has loaded up
Do Until objIE.readyState = READYSTATE_COMPLETE: Loop
'Get document object
Set ieDoc = objIE.document
objIE.Visible = True
'***** Button IDs *****
Set statusFld = ieDoc.all.Item("apprverStatusCode")
'***** END *****
'THIS IS THE ROW WITH THE ERROR:
objIE.document.getElementById(statusFld).Value = "Rejected"
So with the above code, I get "Run time error '424' - Object required".
I've also tried this, which was also not successful:
statusFld.Value = "Rejected"
This is the source code of the website:
<select id="apprverStatusCode" data-code="GROUP_STATUS" data-servicecode="{"preview":"20501","download":"20502"}"
>
<option value="ALL">All</option>
<option value="Rejected">Rejected</option>
<option value="Approved">Approved</option>
</select>
Any ideas why this isn't working?
objIE.document.getElementById("apprverStatusCode").Value = "Rejected"
However that isn't how elements are selected. You need to iterate through the options and add a "selected" attribute to the one you want to select, and remove it from any you do not.
Dim oOptions As MSHTML.IHTMLElementCollection
Dim oOption As MSHTML.IHTMLOptionElement
Set oOptions = objIE.document.getElementById("apprverStatusCode").getElementsByTagName("option")
For Each oOption In oOptions
If oOption.Value = "Rejected" Then
oOption.Selected = True
Else
oOption.Selected = False
End If
Next oOption
I haven't tested this code, so not sure if the datatypes are correct/will work in the for each.
See https://stackoverflow.com/a/38658524/212869 it looks a bit cleaner than mine.
When i go to fatch data using (from date) to (to date), click on show button using vba not working
Also i need suggestion, How can i download csv file from multiple dates
i wanted to download csv file for each date between date range
Dim MP, FD, TD As String
MP = ActiveWorkbook.Name
FD = Sheets("Sheet1").Range("XFA2")
TD = Sheets("Sheet1").Range("XFB2")
Dim IE As New SHDocVw.internetexplorer
Dim HTMLDoc As MSHTML.HTMLDocument
IE.Visible = True
IE.navigate "https://www.mcxindia.com/market-data/bhavcopy"
ShowWindow IE.hwnd, SW_SHOWMAXIMIZED
Do While IE.readyState <> READYSTATE_COMPLETE
Loop
Set HTMLDoc = IE.document
For N = FD To TD
Workbooks(MP).Worksheets("Sheet1").Range("XEX2").Value = (FD)
N1 = Workbooks(MP).Worksheets("Sheet1").Range("XEX3").Value
HTMLDoc.getElementById("txtDate").Value = (N1)
HTMLDoc.getElementById("btnShowDatewise").Click
Next N
Suggest me the codes to click on submit button and how to download multiple date files,since show button takes time to publish data and then i could click on csv tab on rightside penal of webpage
If you are only setting the one day you can do the following which includes a check that the date produces a download file
Option Explicit
Public Sub Download()
Dim ie As New InternetExplorer
With ie
.Visible = True
.Navigate2 "https://www.mcxindia.com/market-data/bhavcopy"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document
.parentWindow.execScript "document.querySelector('#cph_InnerContainerRight_C001_txtDate_hid_val').value='20190201';"
.parentWindow.execScript "document.querySelector('#txtDate').value='20190201';"
.querySelector("#btnShowDatewise").Click
If .querySelectorAll("#cph_InnerContainerRight_C001_lnkExpToCSV").Length > 0 Then
.parentWindow.execScript "__doPostBack('ctl00$cph_InnerContainerRight$C001$lnkExpToCSV','');"
End If
End With
While .Busy Or .readyState < 4: DoEvents: Wend
'.Quit
End With
End Sub
I am attempting to automate a certain process for my business by clicking on certain links on a webpage, inputting business data into a search box and compare it with existing data. I am however, unsuccessful at clicking a javascript based link which also the part of the table using VBA. The website's relevant HTML is as below,
<tr class="odd"> <td> <a onclick="viewCompanyDetails('B214273', '1529481460070');" href="javascript:;">Alinda Infrastructure Fund III (Euro) GP SARL</a></td> <td><a onclick="viewCompanyDetails('B214273', '1529481460070');" href="javascript:;">B214273</a></td> </tr>
Here is my poor attempt at doing the project,
Private Sub CommandButton1_Click()
Set IE = CreateObject("InternetExplorer.Application")
my_url = "https://www.lbr.lu/mjrcs/jsp/DisplayConsultDocumentsActionNotSecured.action?FROM_MENU=true&time=1528967707649¤tMenuLabel=menu.item.companyconsultation"
consoletext = consoletext & "Connection established to Luxembourg Business Registers on www.rcsl.lu via Internet Explorer..." & vbNewLine & vbNewLine
txtConsole.Value = consoletext
consoletext = consoletext & "Looking up Registre De Commerce et des Societes." & vbNewLine & vbNewLine
txtConsole.Value = consoletext
With IE
.Visible = True
.navigate my_url
Do Until Not IE.Busy And IE.readyState = 4
DoEvents
Loop
End With
For Each objlink In IE.document.getElementsByTagName("href")
If objlink.href = "/mjrcs/jsp/DisplayConsultDocumentsActionNotSecured.action?FROM_MENU=true&time=1528969484260¤tMenuLabel=menu.item.companyconsultation" Then
objlink.Click
Exit For
End If
Next objlink
Do Until Not IE.Busy And IE.readyState = 4
DoEvents
Loop
consoletext = consoletext & "Looking up " & Sheets("Results").Range("N1").Value & " in the registry." & vbNewLine & vbNewLine
txtConsole.Value = consoletext
Dim TradeName As String
TradeName = ThisWorkbook.Sheets("Results").Range("Y1").Value
IE.document.getElementById("companyName").Value = TradeName
Set objSubmit = IE.document.getElementsByTagName("input")
For Each btn In objSubmit
If btn.Value Like "Search" Then
btn.Click
End If
Next
Do Until Not IE.Busy And IE.readyState = 4
DoEvents
Loop
For Each entitylink In IE.document.getElementsByClassName("tr")
If entitylink.getElementsByTagName = "a" And entitylink.textcontent = Sheets("Results").Range("N1").Value And entitylink.href = "javascript:;" Then
entitylink.Click
Exit For
End If
Next entitylink
txtXMLpath.Value = ""
End Sub
This is what the webpage content looks like,
enter image description here
I have hidden the name of the entity to protect the identity of the client. I need to click the result on the first row per the image.
I will be much obliged if you could provide any help. Again, I'm a beginner in VBA and have no idea how to proceed here. Please let me know should you require further clarification
You can use .querySelector to get the element you want which is the first with
.document.querySelector("a[onclick='viewCompanyDetails('B214273', '1529481460070');']")
Then you may need to do either:
.document.querySelector("a[onclick='viewCompanyDetails('B214273', '1529481460070');']").Click
or
.document.querySelector("a[onclick='viewCompanyDetails('B214273', '1529481460070');']").fireEvent 'onclick'
CSS selector:
The selector returns 2 items from your HTML but .querySelector will only return the first of these when applying the selector to the HTML. The first is the required "SARL".
More info on .fireEvent method:
fireEvent method: Fires a specified event on the object.
Syntax: object.fireEvent(bstrEventName, pvarEventObject,
pfCancelled)
It has a boolean return value which if TRUE tells you the event was successfully fired.
.querySelector method:
The Document method querySelector() returns the first Element
within the document that matches the specified selector, or group of
selectors. If no matches are found, null is returned.
Syntax: element = document.querySelector(selectors); <== note the ";"
is not used in VBA
Edit:
If .querySelector method is not supported you could try looping the a tags and clicking when a particular string is found e.g.
Dim c As Object, n As Object
Set c = ie.document.getElementsByTagName("a")
For Each n In c
If InStr(1, n.innerText, "Alinda Infrastructure Fund III (Euro) GP SARL") > 0 Then
n.Click
Exit For
End If
Next n
Without more HTML to target the specific a tags of interest you can do a general write out of all a tags with:
Dim c As Object, n As Object, counter As Long
Set c = ie.document.getElementsByTagName("a")
With ActiveSheet
For Each n In c
counter = counter + 1
.Cells(counter, 1) = n.innerText
Next n
End With
More HTML is needed to target this better; perhaps there is a className or Id to identify the element housing these a tags?
For your link to write table to sheet:
Option Explicit
Public Sub GetInfo()
Dim ie As Object
Application.ScreenUpdating = False
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.navigate "https://www.lbr.lu/mjrcs"
While .Busy Or .readyState < 4: DoEvents: Wend '<== Loop until loaded
Dim links As Object, link As Object
Set links = .document.getElementsByTagName("a")
For Each link In links
If link.innerText = "View the person's file" Then
link.Click
Exit For
End If
Next link
While .Busy Or .readyState < 4: DoEvents: Wend
.document.getElementById("companyName").innerText = "Alinda"
.document.getElementsByClassName("button")(0).Click
While .Busy Or .readyState < 4: DoEvents: Wend
Dim hTable As HTMLTable
Set hTable = .document.getElementsByClassName("commonTable")(0)
Dim n As Object, tRow As Object, tCell As Object, tr As Object, td As Object, r As Long, c As Long, hBody As Object
r = 1
With ActiveSheet
Set hBody = hTable.getElementsByTagName("tbody")
For Each n In hBody 'HTMLTableSection
Set tRow = n.getElementsByTagName("tr") 'HTMLTableRow
For Each tr In tRow
Set tCell = tr.getElementsByTagName("td")
c = 1
For Each td In tCell 'DispHTMLElementCollection
.Cells(r, c).Value = td.innerText 'HTMLTableCell
c = c + 1
Next td
r = r + 1
Next tr
Next n
End With
.Quit '<== Remember to quit application
End With
Application.ScreenUpdating = True
End Sub
This is my first try to navigate a IE browser through VBA.
I am trying to:
- go to this webpage https://hb2.bankleumi.co.il/e/Login.html
- fill in the username
- fill the password
- click the "login" button
for now I'm getting the error "Method 'Document' of object 'IWebBrowser2' failed"
I tried to inspect the elements in the html code of the webpage and found their ids but I suppose I'm making some mistake in invoking the methods or approaching the object.
my code is:
Option Explicit
Sub dataFromLeumi()
Dim myPassword As String
myPassword = "somepassword"
Dim myUserName As String
myUserName = "someusername"
Dim loginPath As String
loginPath = "https://hb2.bankleumi.co.il/e/Login.html"
Dim IE As Object
Set IE = CreateObject("InternetExplorer.application")
IE.Visible = True
IE.navigate loginPath
Dim userName As Object
Set userName = IE.document.getattribute("uid")
userName.Item(0).Value = myUserName
Dim password As Object
password = IE.document.getelementbyid("password")
password.Item(0).Value = myPassword
IE.document.getelementbyid("enter").Click
End Sub
What should I change in my code? What do I miss out?
Thanks!
Try this
Sub test()
' open IE, navigate to the desired page and loop until fully loaded
Set ie = CreateObject("InternetExplorer.Application")
my_url = "https://hb2.bankleumi.co.il/e/Login.html"
With ie
.Visible = True
.Navigate my_url
.Top = 50
.Left = 530
.Height = 400
.Width = 400
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
End With
' Input the userid and password
ie.Document.getElementById("uid").Value = "testID"
ie.Document.getElementById("password").Value = "testPW"
' Click the "Search" button
ie.Document.getElementById("enter").Click
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
End Sub
for some reason, VBS below works like a charm in IE 8, but in IE9 on both of my Laptops
I get Object Required at .getElement.
How can I fix this please.
WScript.Quit Main
Function Main
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate "http://desistream.tv/en/index.shtml"
Wait IE
With IE.Document
.getElementByID("login_username").value = "myuser"
.getElementByID("login_password").value = "mypass"
.getElementByID("frmLogin").submit
End With
End Function
Sub Wait(IE)
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
End Sub
Sub IE_OnQuit
On Error Resume Next
WScript.StdErr.WriteLine "IE closed before script finished."
WScript.Quit
End Sub
edit
this is what I got so far in JScript
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run("Chrome www.desistream.tv", 10, true);
WScript.Sleep(500);
You need to use the right names. The names you have given are the Name property, not the ID, so:
.getElementByID("login_username").value = "myuser"
.getElementByID("login_password").value = "mypass"
Should be:
.getElementByID("username").Value = "myuser"
.getElementByID("pass").Value = "mypass"