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