Excel VBA to Enter Data Online With IE and Loop Through Rows - vba

I'm trying to use Excel VBA to pull the info from columns A2-D2 and enter it into the web site and then click the "Next" button. The code below is what I have so far which works fine for entering the info found on row 2 only.
I'm hoping to achieve that IE opens a new window, enters the values in cells A2 through D2, clicks the "Next" button, and then loops to open another new IE window and enters the values in cells A3 through D3 until it hits an empty cell.
Here are the current numbers that I'm using for testing, http://imgur.com/a/88XEF.
Thanks in advance for any suggestions.
Sub FillInternetForm()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
'create new instance of IE. use reference to return current open IE if
'you want to use open IE window. Easiest way I know of is via title bar.
IE.Navigate "https://mygift.giftcardmall.com/Card/Login?returnURL=Transactions"
'go to web page listed inside quotes
IE.Visible = True
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
'pause if needed
Application.Wait Now + TimeValue("00:00:02")
IE.Document.All("CardNumber").Value = ThisWorkbook.Sheets("sheet1").Range("a2")
IE.Document.All("ExpirationMonth").Value = ThisWorkbook.Sheets("sheet1").Range("b2")
IE.Document.All("ExpirationYear").Value = ThisWorkbook.Sheets("sheet1").Range("c2")
IE.Document.All("SecurityCode").Value = ThisWorkbook.Sheets("sheet1").Range("d2")
'presses the next button
Set tags = IE.Document.GetElementsByTagname("Input")
For Each tagx In tags
If tagx.Value = "Next" Then
tagx.Click
Exit For
End If
Next
End Sub

You just need to wrap your code in a loop..
Dim i as integer
i = 2
do while (ThisWorkbook.Sheets("sheet1").cells(i, 1).value <> "")
'your code from Application.wait line to end of next button click
i = i + 1
loop
This assumes an empty row can be identified by column A being empty. You could change the condition on the while loop if this assumption is bad

sorry had to right a new answer because the formatting was going weird
ok makes sense, you just need to move the start of your loop further up the code so it encases the creation of the IE object and the navigation, you should also close the IE window before opening a new one:
move the chunk:
Dim i as integer
i = 2
do while (ThisWorkbook.Sheets("sheet1").cells(i, 1).value <> "")
right up to the top right after:
Sub FillInternetForm()
Add the following lines after the line "Next" right at the bottom but still enclosed by the loop
IE.Quit
Set IE = Nothing

I was able to accomplish what I wanted with the following. Thanks to those that commented.
Sub FillInternetForm()
Range("A2").Select
Do Until IsEmpty(ActiveCell)
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
'create new instance of IE. use reference to return current open IE if
'you want to use open IE window. Easiest way I know of is via title bar.
IE.Navigate "https://mygift.giftcardmall.com/Card/Login?returnURL=Transactions"
'go to web page listed inside quotes
IE.Visible = True
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
'pause if needed
Application.Wait Now + TimeValue("00:00:02")
IE.Document.All("CardNumber").Value = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
IE.Document.All("ExpirationMonth").Value = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
IE.Document.All("ExpirationYear").Value = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
IE.Document.All("SecurityCode").Value = ActiveCell.Value
ActiveCell.Offset(1, -3).Select
'presses the next button
Set tags = IE.Document.GetElementsByTagname("Input")
For Each tagx In tags
If tagx.Value = "Next" Then
tagx.Click
Exit For
End If
Next
Loop
End Sub

Related

Can't assign text to cell with Excel VBA

I'm trying to scrape zip codes from Google. I've been trying to put innertext into a cell, but I think I may be getting a variable mismatch on 2nd to last line.
'This Must go at the top of your module. It's used to set IE as the active window
Sub Automate_IE_Enter_Data()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
Dim HWNDSrc As Long
Dim adds As Variant, add As Variant
Dim addt As String
'Create InternetExplorer 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.google.com/search?ei=djKhW7nELYqs8AO96baoAw&q=1000 Westover Rd kansas city, Mo"
'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 inadvertantly skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop
Do Until IE.ReadyState = 4: DoEvents: Loop
'Webpage Loaded
Application.StatusBar = URL & " Loaded"
'Get Window ID for IE so we can set it as activate window
HWNDSrc = IE.Hwnd
'Set IE as Active Window
'SetForegroundWindow HWNDSrc
Debug.Print "ihgc"
'Unload IE
endmacro:
Set adds = IE.Document.getElementsbyClassName("desktop-title-subcontent")
For Each add In adds
Debug.Print add.innertext
Next
Cells(2, f).Value = add.innertext
End Sub
Couple of things. First and foremost, your loop is unnecessary. I ran your code, and there's nothing to loop. Even if it was necessary, it's being used improperly.
So, in assuming that you in fact do not need a For...Next loop, then you can use the index number of 0 for your collection of IE.Document.getElementsbyClassName("desktop-title-subcontent"), then set your cell reference equal to the innerText property of that collection item.
This brings me to the next issue, your cell reference. Cells(2, f), the f is not a declared variable. If you where actually wanting to use the column "F", then you need to enclose 'F' in double quotes:
Cells(2, "F") or use the column's index of 6, Cells(2, 6)
So, replace this entire portion:
Set adds = IE.Document.getElementsbyClassName("desktop-title-subcontent")
For Each add In adds
Debug.Print add.innertext
Next
Cells(2, f).Value = add.innertext
with this:
Cells(2, "F").Value = IE.Document.getElementsByClassName _
("desktop-title-subcontent")(0).innerText
OPTIONAL
And lastly, I would look into using Early Binding over late binding. It has many advantages, with a possible notable speed improvement.
You would need to set a reference to Microsoft Internet Controls and declare IE as type InternetExplorer vs Object. But that's not going to make or break your code.

Using VBA to click a link

I'm trying next to click a link to view information on a page using VBA to then move on to edit that information with VBA, But trying to figure out how to write the code for it as the ID information changes with each search,
Any ideas on this?
I've looked around and can't seem to understand how to get VBA to pick this line up as the (ID=) and it isn't joined to the same ID as I'm searching for.
There is also serval references for
This is the line of code.
View
This is my current code to do the search for it. Without clicking on the view section yet.
Sub Test()
Dim ie As Object
Dim form As Variant
Dim button As Variant
Dim LR As Integer
Dim var As String
LR = Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To LR
var = Cells(x, 1).Value
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
With ie
.Visible = True
.navigate "*******"
While Not .readyState = READYSTATE_COMPLETE
Wend
End With
'Wait some to time for loading the page
While ie.Busy
DoEvents
Wend
Application.Wait (Now + TimeValue("0:00:02"))
ie.document.getElementById("quicksearch").Value = var
'code to click the button
Set form = ie.document.getElementsByTagName("form")
Application.Wait (Now + TimeValue("0:00:02"))
Set button = form(0).onsubmit
form(0).submit
'wait for page to load
While ie.Busy
DoEvents
Wend
Next x
End Sub
Edited
I've added in the code I think it should be following that link and a bit of tinkering to get it to not error with compiler errors :D, All seems to work but when it get's to the line to click the link it doesn't fail but doesn't even click it. It will then move on to the next one in the list in the spreed sheet, Which is expected.
Following it through with the debugger that shows nothing erroring or failing which is what I expect it to do if the code was wrong or link,
Any help, please ?
This is the code now
Sub Test1()
Dim ie As Object
Dim form As Variant
Dim button As Variant
Dim LR As Integer
Dim var As String
LR = Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To LR
var = Cells(x, 1).Value
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
Dim a
Dim linkhref
linkhref = "/?do_Action=ViewEntity&Entity_ID"
With ie
.Visible = True
.navigate "*******"
While Not .readyState = READYSTATE_COMPLETE
Wend
End With
'Wait some to time for loading the page
While ie.Busy
DoEvents
Wend
Application.Wait (Now + TimeValue("0:00:02"))
ie.document.getElementById("quicksearchbox").Value = var
'code to click the button
Set form = ie.document.getElementsByTagName("form")
Application.Wait (Now + TimeValue("0:00:02"))
Set button = form(0).onsubmit
form(0).submit
'wait for page to load
While ie.Busy
DoEvents
Wend
Application.Wait (Now + TimeValue("0:00:02"))
For Each a In ie.document.getElementsByTagName("a")
If (a.getAttribute("href")) = ("/?do_Action=ViewEntity&Entity_ID=") Then
a.Click
Exit For
Application.Wait (Now + TimeValue("0:00:02"))
While ie.Busy
DoEvents
Wend
End If
Next
Next x
End Sub
This is a copy of the code around the buttons,
This is the code surrounding the buttons,
View
Decom
Log</td>
Thank you.
Use a For to check every <a> tag element and make sure you click the right one. It's true your ID changes, but rest of string is constant, so that's 1 factor. Also, it looks like you always will click where it says View so that's another constant.
With both options, we can develop a simple For..Next that will check every <a> element and will check if those 2 options requirements are fulfilled:
For Each a In ie.document.getElementsByTagName("a")
If Left(a.href, 37) = "/?do_Action=ViewEntity&Entity_ID=" And a.innerText = "View" Then
a.Click
Exit For
Next a
Try it and let's see if this works for you.
If the element href is something like "/?do_Action=ViewEntity&Entity_ID=14287", this if statement is never going to evaluate to True:
(a.getAttribute("href")) = ("/?do_Action=ViewEntity&Entity_ID=")
So the element will never be clicked.
If you know the Entity_ID you want to click you can do:
Dim Entity_ID as Integer
Entity_ID = 14287
If (a.getAttribute("href")) = "/?do_Action=ViewEntity&Entity_ID=" & Cstr(myID) Then a.click
Otherwise just check if the element href contains that url:
If InStr(1, a.getAttribute("href"), linkhref) > 0 Then a.click
EDIT
Ok, using the HTML you posted I am able to access the specified a tag that you requested, by doing this
For Each ele In ie.document.getElementById("searchresults").getElementsByTagName("a")
If InStr(1, ele.href, "do_Action=ViewEntity") > 0 Then
MsgBox "The button is found!"
End If
Next

Crawler & Scraper using excel vba

I am trying to crawl in an intranet URL, so I can get the excel automatically select one of the options from a dropdown menu, then enter a value in a text box, then click on Find to get redirected to another page, where I want to get a value copy to another worksheet in the same workbook, I have created the below, but the code is not working, saying object required. :(
Sub Test()
Dim rng As Range
Set rng = Sheets("sheet1").Range("A1", Sheets("sheet1").Cells.Range("A1").End(xlDown))
Set ie = CreateObject("InternetExplorer.application")
ie.Visible = True
ie.Navigate ("https://gcd.ad.plc.cwintra.com/GCD_live/login/login.asp")
Do
If ie.ReadyState = 4 Then
ie.Visible = False
Exit Do
Else
DoEvents
End If
Loop
ie.Document.forms(0).all("txtUsername").Value = ""
ie.Document.forms(0).all("txtPassword").Value = ""
ie.Document.forms(0).submit
ie.Visible = True
Appliction.Wait (Now + TimeValue("00:00:02"))
DoEvents
For Each cell In rng
ie.Navigate ("https://gcd.ad.plc.cwintra.com/GCD_live/search.asp")
DoEvents
ie.Document.getElementById("cboFieldName").selectedIndex = 6
ie.Document.getElementById("txtFieldValue").Select
SendKeys (cell.Value)
DoEvents
ie.Document.getElementById("cmdFind").Click
Next cell
End Sub

Run Time Error 1004 on Do While Not ActiveCell.Offest(-1, RowCount).Value = ""

I'm trying to write a macro. The macro is supposed to work by the user clicking on the first empty cell in column D. Then it should grab the tracking number to the left in column C. Navigate to the website. Return the delivered date into the first clicked on cell, then basically shift down one row and do the same thing without having to click again on the next row. Loop the process until you encounter the first emtpy cell in column C. This can't start at a particular cell every time because it's an on going spread sheet that's added too every week and this will start close the the bottom. For instance this week where I started was cell D2343. It's not finished code, but any suggestions would be helpful. I am fairly new to coding and extremely new to excel VBA so please bear with me. There's probably a better way to go about this than using activecell, but I'm not sure how. This
Public Sub Tracking()
Dim IE As Object
Dim ReturnValue As String
Dim ProUrl As String
Dim RowCount As Integer
Set IE = CreateObject("InternetExplorer.application")
RowCount = 0
'THIS LINE RETURN THE ERROR
Do While Not ActiveCell.Offset(-1, RowCount).Value = ""
ProUrl = "https://www.rrts.com/Tools/Tracking/Pages/MultipleResults.aspx?PROS=" & ActiveCell.Offset(-1, RowCount).Value
With IE
.Visible = False
.Navigate ProUrl
Do Until Not IE.Busy And IE.readyState = 4: DoEvents: Loop
End With
ReturnValue = Trim(IE.document.getElementsByTagName("Span")(16).innerText)
ActiveCell.Offset(, RowCount).Value = ReturnValue
RowCount = RowCount + 1
Loop
IE.Quit
Set IE = Nothing
End Sub
Any help would be appreciated. Stackoverflow has been a tremendous resource. Thank you.
I think the error may be in your Offset method. The first argument should be the row offset, and the second argument should be the column offset. It seems like you may have that backwards.
Try changing it to:
Do While Not ActiveCell.Offset(RowCount, -1).Value = ""

IE button click with VBA

Can't get the "GO" button to click via VBA on this site: https://finra-markets.morningstar.com/BondCenter/BondDetail.jsp?ticker=C631551&symbol=RDS4242315
Will eventually want to loop code. Should be simple...just can't get this one.
Sub Macro1()
'we define the essential variables
Dim ie As Object
Dim acct
Dim button
Set Rng = Range("B4:B4")
Set Row = Range(Rng.Offset(1, 0), Rng.Offset(1, 0).End(xlDown))
For Each Row In Rng
'add the "Microsoft Internet Controls" reference in your VBA Project indirectly
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.navigate ("https://finra-markets.morningstar.com/BondCenter/BondDetail.jsp?ticker=C631551&symbol=RDS4242315")
While ie.ReadyState <> 4
DoEvents
Wend
Set Cusip = .document.getElementById("ms-finra-autocomplete-box") 'id of the username control (HTML Control)
Cusip.Value = Range("B" & Row.Row).Value
ie.document.getElementsByTagName("submit").Click
End With
Next Row
End Sub
The tag name of your button is not "submit" but "INPUT" ... "submit" is the type.
But watch out, there are more INPUT elements, so your getElementsBy... will return a collection and you need to further dig to find the correct one, e.g. by checking a significant attribute.
Example
' ...
Set ECol = ie.document.getElementsByTagName("input")
For Each IFld In ECol
If IFld.getAttribute("class") = "button_blue autocomplete-go" Then
IFld.Click
Exit For
End If
Next IFld
' ...