VBA Login to IE

joshuaatwork

New Member
Joined
Feb 28, 2013
Messages
13
Hey guys, no formal training but I like to tinker, so I'm working on a tool that will login to a website by button. I pilfered some VBA from somewhere else and got it to work.

Code:
Sub Test()

    Const cURL = "xxxxxxx" 'Enter the web address here
    Const cUsername = "xxxxxxx" 'Enter your user name here
    Const cPassword = "xxxxxxx" 'Enter your Password here
    
    Dim IE As InternetExplorer
    Dim doc As HTMLDocument
    Dim LoginForm As HTMLFormElement
    Dim UserNameInputBox As HTMLInputElement
    Dim PasswordInputBox As HTMLInputElement
    Dim SignInButton As HTMLInputButtonElement
    Dim HTMLelement As IHTMLElement
    Dim qt As QueryTable
        
    Set IE = New InternetExplorer
    
    IE.Visible = True
    IE.Navigate cURL
    
    'Wait for initial page to load
    
    Do While IE.ReadyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop
    
    Set doc = IE.document
    
    'Get the only form on the page
    
    Set LoginForm = doc.forms(0)
    
    'Get the User Name textbox and populate it
    'input name="Email" id="Email" size="18" value="" class="gaia le val" type="text"
 
    Set UserNameInputBox = LoginForm.elements("user")
    UserNameInputBox.Value = cUsername
    
    'Get the password textbox and populate it
    'input name="Passwd" id="Passwd" size="18" class="gaia le val" type="password"


    Set PasswordInputBox = LoginForm.elements("Password")
    PasswordInputBox.Value = cPassword
    
    'Get the form input button and click it
    'input class="gaia le button" name="signIn" id="signIn" value="Sign in" type="submit"
    
    'Set SignInButton = LoginForm.elements("Login")
    'SignInButton.Click
    
    With IE
        .document.forms(0).submit

    End With

    
            
            
    'Wait for the new page to load
    
    Do While IE.ReadyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop
    
    End Sub

But now I've run into trouble trying to get it to work on the next site. It seemed simple enough to change the site, user id, and password. Then find the element name for the new fields, but I just can't get it to work. Can someone point me in the right direction? Below is the html for the site in question. This site has more an organization id, as well as a username and password, but even ignoring that, I can't even get the username input.


Code:
    ****** HTTP-EQUIV="Pragma" CONTENT="NO-CACHE">
    ****** HTTP-EQUIV="CACHE-CONTROL" CONTENT="PRIVATE, NO-CACHE, NO-STORE, MUST-REVALIDATE">
    ****** HTTP-EQUIV="Expires" CONTENT="-1">
    
    ******** ********************>
        function inputValidate() {
            if (document.form1.PASSWD.value == "" ) {
                alert ("Please enter a password to logon");
                return false;
            }
            return commonValidation();
        }

        function commonValidation() {
            if (document.form1.ORG_ID.value == "" ) {
                alert ("Please enter an Organization ID to logon");
                return false;
            }
            if (document.form1.USER_ID.value == "" ) {
                alert ("Please enter a User ID to logon");
                return false;
            }
            if (isNaN(document.form1.ORG_ID.value)) {
                alert ("Please enter a numeric Organization ID to logon");
                return false;
            }
            return true;
        }
        
        //
        // CR75105; Pad String to ensure string has X number of characters
        //
        function padX(number, length)
        {
            var str = '' + number;
            while (str.length < length)
            {
               str = '0' + str;
            }
            return str;
        }                

        //
        // CR75105;Pad String to ensure string always has 2 characters
        //        
        function pad2(number)
        {
            return (number < 10 ? '0' : '') + number;
        }        

        //
        // CR75105;Generate a random string of X length characters
        //
        function genRandomString(strLen)
        {
                var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
                var randomString = '';
                for (var i=0; i < strLen; i++) 
                {
                   var rnum = Math.floor(Math.random() * chars.length);
                   randomString += chars.substring(rnum,rnum+1);
                }
                return randomString;
        }
        
        //
        // CR75105;Generate a token to be stored at logon consisting of date/time (and ms), along with 20 random characters
        //        
        function makeToken()
        {
            var token = '';
            var dt = new Date();
            var dtS = dt.getFullYear() + pad2(dt.getMonth()+1) + pad2(dt.getDate()) + 
                      pad2(dt.getHours()) + pad2(dt.getMinutes()) + pad2(dt.getSeconds()) + 
                      padX(dt.getMilliseconds(),3);
            token = dtS + '-' + genRandomString(20);
            document.form1.hidden_logontoken.value = token;
        }

        //
        // CR75105; Function to be run when the page is loaded
        //        
        function startPage()
        {
            makeToken();
            form1.ORG_ID.focus();
        }

    *********>
    
    ******** ********************>
        if (top.location == self.location ) {
            top.location.href = "logonframe.htm";
        }
    *********>
    








    
        
    
[TABLE="class: heading, width: 100%"]
<tbody>[TR]
[TD]            MERS[SUP]®[/SUP] OnLine 
[/TD]
[/TR]
</tbody>[/TABLE]


<form id="form1" name="form1" target="_top" action="validatelogon.jsp" method="post" autocomplete="off"> 




    
        
    
    
        
        
    
    
        
        
    
    
        
        
    
    
        
    
[TABLE="class: entry"]
<tbody>[TR]
[TH="colspan: 2"]            Please enter your logon credentials below.
[/TH]
[/TR]
[TR]
[TD="class: label"]            Organization ID:[/TD]
[TD="width: 50%"]            <input id="ORG_ID" name="ORG_ID" size="15" maxlength="7">[/TD]
[/TR]
[TR]
[TD="class: label"]            User ID:[/TD]
[TD]            <input id="USER_ID" name="USER_ID" size="15" maxlength="8">[/TD]
[/TR]
[TR]
[TD="class: label"]            Password:[/TD]
[TD]            <input name="PASSWD" size="15" maxlength="12" type="password">[/TD]
[/TR]
[TR]
[TD="colspan: 2"]        

        [/TD]
[/TR]
</tbody>[/TABLE]




    
        
    
[TABLE="width: 100%"]
<tbody>[TR]
[TD="class: ctr"]            If you have forgotten your password, please enter your Organization ID and User ID and click "Forgot My Password".
[/TD]
[/TR]
</tbody>[/TABLE]



    
        
    
[TABLE="width: 100%"]
<tbody>[TR]
[TD]            [/TD]
[/TR]
</tbody>[/TABLE]

</form>


    
    
        
    
    
    
        
        
    
        
    
    
        
    
    
        
    
    
        
        
    
[TABLE="width: 100%"]
<tbody>[TR]
[TD="class: ctr, colspan: 2"]            The MERS[SUP]®[/SUP] OnLine system hours are Monday through Saturday 7:00 am to 10:00 pm Eastern Time.
[/TD]
[/TR]
[TR]
[TD="class: ctr, colspan: 2"]            The 1st and 3rd Sundays of each month are system maintenance windows. 
The
             maintenance window is from 7:00 am to 11:00 pm Eastern Time.
[/TD]
[/TR]
[TR]
[TD="class: ctr, colspan: 2"]            If you have any questions pertaining to MERS[SUP]®[/SUP] OnLine ,
            please contact the MERSCORP Holdings Help Desk at 1-888-680-6377

            or via email to [EMAIL="helpdesk@mersinc.org"]helpdesk@mersinc.org[/EMAIL]
            . Please include your name and telephone number with the email.
[/TD]
[/TR]
[TR]
[TD="class: ctr, colspan: 2"]            [HR][/HR][/TD]
[/TR]
[TR]
[TD="class: ctr, colspan: 2"]            Copyright© 2012 by MERSCORP Holdings, Inc. 1-800-646-MERS (6377)

            Other products or company names are or may be trademarks

            or registered trademarks and are the property of

            their respective holders.
[/TD]
[/TR]
[TR]
[TD="class: ctr, width: 50%"]            [URL="http://www.microsoft.com/windows/ie/downloads/default.asp"][IMG]http://www.mrexcel.com/images/msie_button.gif[/IMG] [/URL]
            MERS[SUP]®[/SUP] System Application is best viewed with IE
[/TD]
[TD="class: ctr, width: 50%"]            [URL="http://www.eds.com"][IMG]http://www.mrexcel.com/images/HP_Blue_RGB_72_SM.GIF[/IMG] [/URL][/TD]
[/TR]
</tbody>[/TABLE]






    ****** HTTP-EQUIV="Pragma" CONTENT="NO-CACHE">
    ****** HTTP-EQUIV="CACHE-CONTROL" CONTENT="PRIVATE, NO-CACHE, NO-STORE, MUST-REVALIDATE">
     ****** HTTP-EQUIV="Expires" CONTENT="-1">
 

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand
Thanks John_w! I knew the input fields were incorrect, I pasted in the sub that was working for a different site. I made the changes you suggested, and changed the input fields and it's working perfectly (with a little adjustment to the submit portion as well). Thanks again...


If you don't mind, could you explain why my original code didn't work?
 
Upvote 0
If you don't mind, could you explain why my original code didn't work?
Because IE.document is the frameset. Put these two lines in the code and compare their outputs:
Code:
    MsgBox IE.document.body.outerHTML
    MsgBox IE.document.frames("main").document.body.outerHTML
 
Upvote 0
Where can I got to figure that out for myself? The code I posted originally worked for the original site that I tried: https://wholesale.flagstar.com/Lending/public/home.jsp

The reason I ask is because I'm trying to do the same thing for a list of 10 sites, and I'd love to be able to do this myself without bugging anyone for each site that I go to.

For example, I ran into trouble the next site that I tried with both the original code, and the modified code you gave me. When I ran the code you gave me to explain the difference, I get this:

"MsgBox IE.document.body.outerHTML"
Code:
< FRAMESET frameSpacing=0 border=0 cols=* frameBorder=NO rows=110,554* >< FRAME noResize src="wff_loginHeader.html" frameBorder=NO name=Top scrolling=no >< FRAME src="wff_login.jsp" frameBorder=NO name=Body>< /FRAMESET >
"MsgBox IE.document.frames("main").document.body.outerHTML"
Code:
Run-time error'-2147352573 (80020003)':
Member not found.

If you need, the new site is https://ilnet.wellsfargo.com/ilonline/funding/index.html (I'm in the mortgage industry)
 
Upvote 0
"MsgBox IE.document.body.outerHTML"
Code:
< FRAMESET frameSpacing=0 border=0 cols=* frameBorder=NO rows=110,554* >< FRAME noResize src="wff_loginHeader.html" frameBorder=NO name=Top scrolling=no >< FRAME src="wff_login.jsp" frameBorder=NO name=Body>< /FRAMESET >
"MsgBox IE.document.frames("main").document.body.outerHTML"
Code:
Run-time error'-2147352573 (80020003)':
Member not found.
Look carefully at that HTML - the frame name you want is "Body", not "main", therefore the following should work:
Code:
MsgBox IE.document.frames("Body").document.body.outerHTML
The following shows the URL of the Body frame - the src attribute (a relative link in this case) from the above HTML combined with the site URL.
Code:
Msgbox IE.document.frames("Body").document.parentWindow.Location

Every web site is different and therefore requires different coding. The sites in this thread use frames which is quite rare nowadays. Some techniques work on some sites, not others. A lot of VBA coding for IE/HTML automation is trial and error and practice, practice, practice to learn the various methods, get familiar with HTML tags, a bit of Javascript, etc., etc. Always use early binding (of MS Internet Controls - the IE object - and MS HTML Object Library), set via Tools - References menu in the VBA project. Always use Option Explicit.

Here is a list of useful IE HTML automation references:

Internet Explorer Development - Hosting and Reuse

WebBrowser Control

InternetExplorer object (Internet Explorer)

HTML Elements

HTML/XHTML Reference (Internet Explorer)

HTML and DHTML Reference

VBA web services

vba_corner: Working with Internet Explorer Using VBA
 
Upvote 0
Thanks again John_w, this is very helpful. Hopefully I'll be able to get my way through these sites, and I'll be sure to read the material you provided before asking any more questions. I appreciate all your help!
 
Upvote 0
John_w,I'm here once again to beg for your help. We recently switched to IE10 (from IE9) in my office and it broke a few of my macros. Do you happen to know about changes that would make this happen?

The error I get is: Compile error: Object library feature not supported.
It happens when I get to this line:
Code:
Set doc = ie.document.frames("main").document


Here is the website: https://www.mersonline.org/mers/security/logonframe.htm

And this is the code I am using.
Code:
Sub MERS_Login()

    Dim cURL As String
    cURL = Worksheets("Sheet1").Range("B7").Value
    Dim cOrgID As String
    cOrgID = Worksheets("Sheet1").Range("C7").Value
    Dim cUsername As String
    cUsername = Worksheets("Sheet1").Range("D7").Value
    Dim cPassword As String
    cPassword = Worksheets("Sheet1").Range("E7").Value
    
    Dim ie As InternetExplorer
    Dim doc As HTMLDocument
    Dim LoginForm As HTMLFormElement
    Dim UserNameInputBox As HTMLInputElement
    Dim PasswordInputBox As HTMLInputElement
    Dim OrgIDInputBox As HTMLInputElement
    Dim SignInButton As HTMLInputButtonElement
    Dim HTMLelement As IHTMLElement
    Dim qt As QueryTable
        
    Set ie = New InternetExplorer
    
    ie.Visible = True
    ie.Navigate cURL
    
    'Wait for initial page to load
    
    Do While ie.readyState <> READYSTATE_COMPLETE Or ie.Busy: DoEvents: Loop
    
    Set doc = ie.document.frames("main").document
    
    'Get the only form on the page
    
    Set LoginForm = doc.forms(0)
        
    'Get the User Name textbox and populate it
  
    Set OrgIDInputBox = LoginForm.elements("ORG_ID")
    OrgIDInputBox.Value = cOrgID
        
    'Get the User Name textbox and populate it

    Set UserNameInputBox = LoginForm.elements("USER_ID")
    UserNameInputBox.Value = cUsername
    
    'Get the password textbox and populate it

    Set PasswordInputBox = LoginForm.elements("PASSWD")
    PasswordInputBox.Value = cPassword
    
    'Get the form input button and click it
    
    Set SignInButton = LoginForm.elements("loginButton")
    SignInButton.Click

    'Wait for the new page to load
    
    Do While ie.readyState <> READYSTATE_COMPLETE Or ie.Busy: DoEvents: Loop
    
    End Sub

Again, your help is greatly appreciated!
 
Upvote 0

Forum statistics

Threads
1,223,227
Messages
6,170,848
Members
452,361
Latest member
d3ad3y3

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top