Log In to page automatically by filling in HTML elements with VB.NET - vb.net

I'm attempting to migrate a script written in VBA inside a database into an application that I've written in VB.NET, as an added feature.
I understand that the VBA and VB.NET languages are very different and I've been having a hard time trying to migrate the section of code that I need.
I need to open an Internet Explorer page, fill in two textboxes that would be used for a username and password, and press the submit / login button automatically.
In VBA, I was able to do this using the below code.
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
'Ignore errors
On Error GoTo Err_Clear
MyURL = Address
Set MyBrowser = New InternetExplorer 'Open Internet Explorer
MyBrowser.Silent = True 'Silence popups & Errors
MyBrowser.Navigate MyURL 'Browse
MyBrowser.Visible = True 'Obvious
Do
'Wait till finished
Loop Until MyBrowser.ReadyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.Document
'Enter user / password
For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input")
If MyHTML_Element.Name = ("username") Then
MyHTML_Element.Value = Username 'Variable to be passed to sub
ElseIf MyHTML_Element.Name = ("password") Then
MyHTML_Element.Value = Password 'Variable to be passed to sub
ElseIf MyHTML_Element.Type = "submit" Then
MyHTML_Element.Click: Exit For
End If
Next
Err_Clear:
If Err <> 0 Then
'Debug.Assert Err = 0
Err.Clear
Resume Next
End If
When moving this to VB.NET, even after adding the references I'd used for Microsoft Internet Controls, and Microsoft HTML Object library, I receive several errors such as:
Dim MyHTML_Element As IHTMLElement '"ITHMLElement" is ambiguous in the namespace 'mshtml'
Loop Until MyBrowser.Readystate = READYSTATE_COMPLETE 'Not declared
I've used Visual Basic before, but haven't used it to manipulate values of HTML pages within a web browser, and haven't been able to find much regarding this in VB.NET online.
I'm hoping someone can provide some insight into this for me, or point me in the right direction, thanks in advance!

I found an answer today on another site.
I was able to use the following vb.net code to identify each element, fill in it's value with a username and password, and then click a submit button (assuming the submit button's Element ID is known)
Dim theElementCollection As HtmlElementCollection = Me.WebBrowser1.Document.GetElementsByTagName("input")
For Each curElement As HtmlElement In theElementCollection
Dim controlName As String = curElement.GetAttribute("name").ToString.ToUpper
If controlName.ToUpper = "USERNAME" Then
curElement.SetAttribute("Value", Username)
ElseIf controlName.ToUpper = "PASSWORD" Then
curElement.SetAttribute("Value", Password)
WebBrowser1.Document.GetElementById("submitButton").InvokeMember("click") 'click button

Related

How Do I enter username and Password on a webpage?

Q1)How do I enter the password and username on this webpage"https://.com/1/19/login.esp" ?
I have written the code to access the webpage:
Sub login()
Dim IE As Object
Const navOpenInNewTab = &H800
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "https://esp"
End Sub
Q2) what createobject should I use to access google chrome?
Thnx in advance
To find items on a webpage to select through VBA, you need to step into the Developer tools on the webpage by pressing F12.
Once there, you can find the elements you want to call by "stepping into" the code on the page and selecting the items you wish VAB to select.
Here is how that is done:
Then select the username box:
After selecting this box, the code in the developer box will be highlighted, telling you what the code is that is linked to the item you pressed.
Here is the now highlighted code for the username box:
We have three options to select the item on the page:
IE.document.getElementById (find the ID= in the code, here id='USERNAME')
IE.document.getElementsByName (find the Name= in the the code, here name='USERNAME')
IE.document.getElementsByclassname (find the class= in the code. In this case, class='focus')
*Note: Try to use to use the ID first, then name, then class as only 1 element on the page will have that 1 ID, but multiple items can have the same name or class, or its guaranteed to work if you have the correct ID.
Dim IE As Object ' InternetExplorer.Application
Dim UserN As Object 'username field
Dim PW As Object 'password field
Dim LoginButton As Object 'Login button
'enter username and password in textboxes
Set UserN = IE.document.getElementByID("USERNAME")
'fill in first element named "username", assumed to be the login name field
UserN(0).Value = ""
Set PW = IE.document.getElementsByName("PASSWORD")
'fill in first element named "password", assumed to be the password field
PW(0).Value = ""
Then you need to find the botton on the page, and click it.
Here is some code for that:
'After entering in the user/pass, we need to click the button.
Dim objCollection As Object
Set objCollection = IE.document.getElementById("loginbutton")
objCollection.Click
There is a ton more info out there and more code on how to properly use each selection method, so this is just the barebones to get you started.
Searching for 'VBA IE automation' will get you some good results to work with.
Sub login()
Dim IE As Object
Dim HTMLDoc As Object
Dim objCollection As Object
Const navOpenInNewTab = &H800
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "https://ogin.esp"
Do While IE.Busy Or IE.ReadyState <> 4: Loop
Set HTMLDoc = IE.document
With HTMLDoc
HTMLDoc.getElementById("USERNAME").Value = "yyyy"
HTMLDoc.getElementById("PASSWORD").Value = "xxxxx"
End With
Set objCollection = IE.document.getElementById("loginbutton")
objCollection.Click
End Sub
This code works....

Issue with finding element on Amazon Seller homepage with VBA code

I recently came across a new problem while working with my Excel VBA code in order to automate the input a value from a cell (order number) into Amazon's search box and searching for the order. I can't seem to locate the proper object to reference the search button on the homepage of the Amazon Seller home page in order to click and proceed. My code is this:
Option Explicit
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Sub MyAmazonSeller()
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
Dim oSignInLink As HTMLLinkElement
Dim oInputEmail As HTMLInputElement
Dim oInputPassword As HTMLInputElement
Dim oInputSigninButton As HTMLInputButtonElement
Dim oInputSearchOrder As HTMLInputElement
Dim oInputSearchButton As HTMLInputButtonElement
MyURL = "https://sellercentral.amazon.com/gp/homepage.html"
Set MyBrowser = New InternetExplorer
' Open the browser and navigate.
With MyBrowser
.Silent = True
.Navigate MyURL
.Visible = True
Do
DoEvents
Loop Until .ReadyState = READYSTATE_COMPLETE
End With
' Get the html document.
Set HTMLDoc = MyBrowser.Document
' See if you have the sign in link is because you are in the main
' page
Set oSignInLink = HTMLDoc.getElementById("signin-button-container")
If Not oSignInLink Is Nothing Then
oSignInLink.Click
Do
DoEvents
Loop Until MyBrowser.ReadyState = READYSTATE_COMPLETE
End If
' Get the email field and the next button
Set oInputEmail = HTMLDoc.getElementById("username")
Set oInputPassword = HTMLDoc.getElementById("password")
' Click the button and wait
oInputEmail.Value = "xxxxxxxxx#xxxxxx.net"
' Get the password field and the sign in button
Set oInputPassword = HTMLDoc.getElementById("password")
Set oInputSigninButton = HTMLDoc.getElementById("sign-in-button")
' Click the button and wait
oInputPassword.Value = "xxxxxxxx"
oInputSigninButton.Click
Do
DoEvents
Loop Until MyBrowser.ReadyState = READYSTATE_COMPLETE
Set oInputSearchOrder = HTMLDoc.getElementById("sc-search-field")
oInputSearchOrder.Value = "110-7706193-5695453"
Set oInputSearchButton = HTMLDoc.getElementByClassName("sc-search-button")
oInputSearchButton.Click
Do
DoEvents
Loop Until MyBrowser.ReadyState = READYSTATE_COMPLETE
Err_Clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub
The section right before the Err_Clear is the new snippet of code I've been trying to modify and work with. It seems that the search button does not have a proper ID, so therefore is more difficult to reference. I am getting an Error 91 every time the code gets to the second to last snippet.

Using VBA to control IE to login to a website

I'm new to this, but I'm practising, and it seemed to me that logging into my Institute's website ought to be the easiest thing in the world. Right? Well, it's driving me crazy.
Specifically, the program fails at
page.Document.getElementById("edit-name").Value = 1234
Run time error 424 "object required"
Also, and I'm not sure if this is related, when I type "page." the VBA editor helpfully provides a list of options, and I select Document. When I type the second "." to get "page.Document." I do not then get a further list of options.
Here's the complete program, and thanks for any help
Public Sub MyLogin()
'This uses early binding
'In menu at top of page - Tools...Reference.... Microsoft Internet Controls and Microsoft HTML Object Library must both be ticked
Dim page As InternetExplorer
Set page = New InternetExplorer
page.Visible = True
Dim MyLink As Object
'Login at Institute website
page.Navigate "http://www.actuaries.org.uk/"
Do While page.Busy Or page.ReadyState <> 4
DoEvents
Loop
For Each MyLink In page.Document.Links
If InStr(MyLink.href, "/user") Then MyLink.Click: Exit For
Next MyLink
Do While page.Busy Or page.ReadyState <> 4
DoEvents
Loop
'Are now at the login page
'Enter username, password and click
page.Document.getElementById("edit-name").Value = 1234
page.Document.getElementById("edit-pass").Value = "01/01/1977"
page.Document.getElementById("edit-submit").Click
End Sub
Specifically, the program fails at page.Document.getElementById("edit-name").Value = 1234
Nothing wrong with that line.
One reason that I can think of is that your For Loop is not executed. To avoid that, directly navigate to the relevant url. This trimmed version works for me.
Sub Sample()
Dim sUrl As String: sUrl = "https://www.actuaries.org.uk/user"
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate sUrl
Do While ie.readystate <> 4: DoEvents: Loop
ie.Document.getElementById("edit-name").Value = 1234
End Sub

VBA: Wait until browser loads more than once

I've been working on a program to fill up a form after the webpage is loaded, its working well with this:
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
After this my code loads, fills up the form and the click the log in button.
Here comes the problem, i've been trying to click a button right after the new page loads, so i tried the same loop method to accomplish this, but it is not working.
I said to myself, this can't be, it has to work!, so i tried making a code for a search on youtube and for my surprise it did work, it searched a video and then i could select the one i wanted.
So if it does work, why it doesnt with my login page?
I noticed the page does not reach the next page right away after logging in, it loads a page and then quickly it loads another one and reroutes to that one.
Do you have any idea how to wait until the browser reaches that point?
whole code until now:
Private Sub CommandButton3_Click()
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
On Error GoTo Err_Clear
MyURL = "url"
Set MyBrowser = New InternetExplorer
MyBrowser.Silent = True
MyBrowser.navigate MyURL
MyBrowser.Visible = True
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
HTMLDoc.all.user.Value = "user"
HTMLDoc.all.pass.Value = "pass"
For Each MyHTML_Element In HTMLDoc.getElementsByTagName("img")
If MyHTML_Element.getAttribute("src") = "url" Then MyHTML_Element.Click: Exit For
Next
Set MyBrowser.document = HTMLDoc
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
For Each MyHTML_Element In HTMLDoc.getElementsByTagName("img")
If MyHTML_Element.getAttribute("name") = "name" Then MyHTML_Element.Click: Exit For
Next
Err_Clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub

VBA - Addressing Internet Explorer tabs

Strangely enough I didn't find any information on the topic and I'm currently stuck at the point where I managed to open a new tab in an instance of IE by programmatically clicking a button, but I haven't the faintest clue of how to address the new tab in order to get information from there (the button basically brings up a new tab with the result of a search).
This is basically a straightforward question, but I'm including my code anyway:
Sub AddInfoFromIntranet()
Dim Ie As SHDocVw.InternetExplorer
Dim URL As String
Dim iFrames As MSHTML.IHTMLElementCollection
Dim iFrame As MSHTML.HTMLFrameElement
Dim Doc As MSHTML.HTMLDocument
Dim InputBox As MSHTML.IHTMLElementCollection, htmlButton, allTags, Tag
' Opens Intranet - yeah, sadly it's not a public web page
URL = "{My intranet website}"
Set Ie = New SHDocVw.InternetExplorer
With Ie
.navigate URL
.Visible = True
While .Busy Or .readyState <> READYSTATE_COMPLETE: DoEvents: Wend
Set Doc = .document
End With
' Gets top_window frame and navigates to it, then inserts the name to search
Set iFrames = Doc.getElementsByName("top_window")
If Not iFrames Is Nothing Then
Set iFrame = iFrames(0)
Ie.navigate URL & iFrame.src
While Ie.Busy Or Ie.readyState <> READYSTATE_COMPLETE: DoEvents: Wend
Set InputBox = Doc.getElementsByName("Nachnamevalue")
If Not InputBox Is Nothing Then InputBox(0).Value = "test"
' Clicks on "search"
Set allTags = Doc.getElementsByTagName("input")
For Each Tag In allTags
If Tag.Value = "suchen" Then
Tag.Click
Exit For
End If
Next
' Here a new tab is opened, must find info in this tab
While Ie.Busy Or Ie.readyState <> READYSTATE_COMPLETE: DoEvents: Wend
' HERE I HAVE NO CLUE WHAT TO WRITE. THE CODE ABOVE WORKS FLAWLESSLY
End If
Set Doc = Nothing
Set iFrames = Nothing
Set iFrame = Nothing
Set InputBox = Nothing
Set allTags = Nothing
Set Ie = Nothing
Ie.Quit
End Sub
Now, is there a way to address a tab by: 1) its name (and where do I find it) 2) its position in browser 3) the status (if it is "active") ?
Bonus questions: since I am new to VBA and Internet Explorer interaction, what exactly are the variables: htmlButton, allTags, Tag ? Also, could anyone explain if I need to set all the variables at the end to nothing, or I just need to set the Internet Explorer to nothing?
Thanks in advance!
See below for a function you can use to get an open IE document window - I don't think IE exposes any simple (VBA-accessible) API for working directly with tabs or determining whether a specific tab is active.
allTags is a collection of DOM elements with type "" , and Tag is a single memeber of that collection.
You do not have to set objects to Nothing before exiting a Sub (though some people still do that) - the VBA runtime will take care of that for you.
Sub TestGetIE()
Dim IE As Object
Set IE = GetIE("http://stackoverflow.com")
If Not IE Is Nothing Then
IE.document.execCommand "Print", False, 0
End If
End Sub
'Get a reference to an open IE window based on its URL
Function GetIE(sLocation As String) As Object
Dim objShell As Object, objShellWindows As Object, o As Object
Dim sURL As String
Dim retVal As Object
Set retVal = Nothing
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
For Each o In objShellWindows
sURL = ""
On Error Resume Next
'check the URL and if it's the one you want then
' assign it to the return value
sURL = o.document.Location
On Error GoTo 0
'Debug.Print sURL
If sURL Like sLocation & "*" Then
Set retVal = o
Exit For
End If
Next o
Set GetIE = retVal
End Function