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
Related
I am trying to extract a table from Drainage Services Department. I have wrote below VBA code, but it does not work. I guess the reason is because this table is JavaScript. Any idea to solve this problem?
Sub DSD()
Dim ie As New InternetExplorer
Dim html As New HTMLDocument
Dim url As String
url = "https://www.dsd.gov.hk/EN/Tender_Notices/Current_Tenders/index.html"
ie.Visible = False
ie.navigate url
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
Set html = ie.document
Dim lists As IHTMLElementCollection
Dim anchorElements As IHTMLElementCollection
Dim ulElement As HTMLUListElement
Dim liElement As HTMLLIElement
Dim row As Long
Set lists = html.getElementsByClassName("ncol-md-12 result")
row = 1
For Each ulElement In lists
For Each liElement In ulElement.getElementsByTagName("tbody")
Set anchorElements = liElement.getElementsByTagName("td")
If anchorElements.Length > 0 Then
Cells(row, 1) = anchorElements.Item(0).innerText
row = row + 1
End If
Next liElement
Next ulElement
ie.Quit
End Sub
I am trying to scrape the table from this website.
UPDATE
Try this instead. I simply gave it some time to load everything into the lists object that you have set up and that did the trick.
Sub DSD()
Dim ie As New InternetExplorer
Dim html As New HTMLDocument
Dim url As String
url = "https://www.dsd.gov.hk/EN/Tender_Notices/Current_Tenders/index.html"
ie.Visible = False
ie.navigate url
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
Set html = ie.document
Dim lists As IHTMLElementCollection
Dim anchorElements As IHTMLElementCollection
Dim ulElement As HTMLUListElement
Dim liElement As HTMLLIElement
Dim row As Long
'you had put "ncol-md-12 result" it is actually named "col-md-12 result"
Set lists = html.getElementsByClassName("col-md-12 result")
row = 1
''application needs time to load everything into lists.
Application.Wait (Now + TimeValue("00:00:01"))
''or with a loop
''Do While i < 1000
''DoEvents
''i = i + 1
''Loop
For Each ulElement In lists
For Each liElement In ulElement.getElementsByTagName("tbody")
Set anchorElements = liElement.getElementsByTagName("td")
If anchorElements.Length > 0 Then
Debug.Print anchorElements.Item(0).innerText
Cells(row, 1) = anchorElements.Item(0).innerText
row = row + 1
End If
Next liElement
Next ulElement
ie.Quit
End Sub
I am trying to use sources on google and on this site to help me but I am struggling to enter a username and password to a input box on a login page.
The page is on a local network on our work server.
The HTML code for the login page:
<TD background=/frontend/images/greenback.gif width=302><INPUT maxLength=32 name=username> </TD>
<TD background=/frontend/images/greenback.gif width=302><INPUT maxLength=32 type=password value="" name=password> </TD>
So far I have tried:
Sub Test()
On Error Resume Next
Dim sUrl As String: sUrl = "https://workplace.plus.net/index.html?"
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate sUrl
Do While ie.readystate <> 4: DoEvents: Loop
ie.document.getElement.Name("username").Value = 1234
End Sub
I have also tried:
ie.document.getElement.Name("username").Value = 1234
ie.document.getElement.Id("username").Value = 1234
ie.document.getElement.Class("username").Value = 1234
ie.document.getElement.Type("username").Value = 1234
ie.document.getElementByClassName("username").Value = 1234
ie.document.getElementById("username").Value = 1234
ie.document.getElementByName("username").Value = 1234
ie.document.getElementByType("username").Value = 1234
The thing is I used this same code on google with the ID button and it works. Is there something I am not taking into consideration?
Here i'm using the facebook login page. You can put any other link to login, put sUser as string and sPass as string. Assigned the values you want to input. Application.Wait (Now + TimeValue("00:00:02")) is the time between loading the page and add login id and password. On the other hand will pass the user id and password IE.Document.all.Item("email").Value = sUser. Try this code please
Sub facebookPost()
Dim IE As Object
Dim sUser As String, sPass As String
sUser = "1234"
sPass = "1234"
Set IE = CreateObject("INTERNETEXPLORER.Application")
IE.Navigate ("www.Facebook.com")
IE.Visible = True
Do While IE.Busy: DoEvents: Loop
Application.Wait (Now + TimeValue("00:00:02"))
IE.Document.all.Item("email").Value = sUser
IE.Document.all.Item("pass").Value = sPass
IE.Document.all.Item("loginbutton").Click
End Sub
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
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