VBA to login to a website ( entering username and pass and hit enter )

qarbiq

New Member
Joined
Jan 4, 2014
Messages
20
so by searching alot i put a code together to automatically login to a page that i want , the following code works fine with Gmail, but not with the login page that i want, my login HTML code on the form section looks like this
</SPAN>
<</SPAN>div</SPAN> id</SPAN>="divLogin"></SPAN>
<</SPAN>div</SPAN> id</SPAN>="divLoginImage"></SPAN>
<</SPAN>div</SPAN> class</SPAN>="form-background"></< SPAN>div</SPAN>></SPAN>
<</SPAN>div</SPAN> class</SPAN>="form-content"></SPAN>
<</SPAN>form</SPAN> name</SPAN>="loginForm" </SPAN>method</SPAN>="post"></SPAN>
<</SPAN>table</SPAN>></SPAN>
<</SPAN>tr</SPAN>></SPAN>
<</SPAN>td</SPAN> class</SPAN>="label"></SPAN>Username</SPAN></< SPAN>td</SPAN>></SPAN>
</< SPAN>tr</SPAN>></SPAN>
<</SPAN>tr</SPAN>></SPAN>
<</SPAN>td</SPAN>><</SPAN>input</SPAN> type</SPAN>="text" </SPAN>name</SPAN>="login_name" </SPAN>size</SPAN>="30"/></< SPAN>td</SPAN>></SPAN>
</< SPAN>tr</SPAN>></SPAN>
<</SPAN>tr</SPAN>></SPAN>
<</SPAN>td</SPAN> class</SPAN>="label"></SPAN>Password</SPAN></< SPAN>td</SPAN>></SPAN>
</< SPAN>tr</SPAN>></SPAN>
<</SPAN>tr</SPAN>></SPAN>
<</SPAN>td</SPAN>><</SPAN>input</SPAN> type</SPAN>="password" </SPAN>name</SPAN>="login_password" </SPAN>size</SPAN>="30" </SPAN>AUTOCOMPLETE</SPAN>="off"/></< SPAN>td</SPAN>></SPAN>
</< SPAN>tr</SPAN>></SPAN>
<</SPAN>tr</SPAN>></SPAN>
<</SPAN>td</SPAN>><</SPAN>input</SPAN> type</SPAN>="button" </SPAN>name</SPAN>="enter" </SPAN>value</SPAN>="Login" </SPAN>class</SPAN>="button" </SPAN>*******</SPAN>="mxSubmit()"/></SPAN>
<</SPAN>br</SPAN>><</SPAN>br</SPAN>><</SPAN>br</SPAN>></SPAN>



and here is my code can you please let me know what i am doing wrong please ???? my code opens the login page and then do not do anything at all ! and then i get undefined error on excel NOTE: i am not including the link becasue it will not work outside of our company, if you can help me with this , you saved me alot !!!! please help me if you know what the problem is.. Thank you</SPAN>

Code:
Private Sub Enovia_Login_Click()</SPAN>
    Const cURL = "www.thatwebsitename.com"  'Enter the web address here
    Const cUsername = "myusername" 'Enter your user name here
    Const cPassword = "mypass!!!" '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
   
    'Set doc = IE.Document.frames("divLogin").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("login_name")
    UserNameInputBox.Value = cUsername
   
 
   
   
   
    'Get the password textbox and populate it
    'input name="Passwd" id="Passwd" size="18" class="gaia le val" type="password"</SPAN>

    Set PasswordInputBox = LoginForm.elements("login_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("enter")
    SignInButton.Click
           
    'Wait for the new page to load
   
    Do While IE.ReadyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop</SPAN>
End Sub
</SPAN>
 

Excel Facts

Get help while writing formula
Click the italics "fx" icon to the left of the formula bar to open the Functions Arguments dialog. Help is displayed for each argument.
I tested this by logging into my Google account. I guess this is what you are trying to do as the control id's are the same. If not, then the code is untested.
Update the constants with your own values.
See highlighted (red) for the relationship between the control id's and code.

Rich (BB code):
Option Explicit


Const url = "https://accounts.google.com/Login?hl=EN"
Const user = "myUsername"
Const pwd = "myPassword"




Sub main()
   Dim ie As Object
   
   Set ie = CreateObject("InternetExplorer.Application")
   ie.navigate url

   'wait until the page loads
   Do While ie.ReadyState <> 4
      DoEvents
   Loop
   ie.Visible = True
   
   With ie.document
      'input name="Email" id="Email" size="18" value="" class="gaia le val" type="text"
      .GetElementById("Email").Value = user
      
       'input name="Passwd" id="Passwd" size="18" class="gaia le val" type="password"
       .GetElementById("Passwd").Value = pwd
       
       'input class="gaia le button" name="signIn" id="signIn" value="Sign in" type="submit"
       .GetElementById("signIn").Click
   End With
End Sub
 
Upvote 0
Thank you for the reply, i already changed those with mine that matches the one in the HTML of the page, but if you notice it dosnt have ID value also everything related to LOGIN are inside <</SPAN>div</SPAN> id</SPAN>="divLogin"> i dont know how to tell excel to use this DIVLOGIN ! </SPAN>




I tested this by logging into my Google account. I guess this is what you are trying to do as the control id's are the same. If not, then the code is untested.
Update the constants with your own values.
See highlighted (red) for the relationship between the control id's and code.

Rich (BB code):
Option Explicit


Const url = "https://accounts.google.com/Login?hl=EN"
Const user = "myUsername"
Const pwd = "myPassword"




Sub main()
   Dim ie As Object
   
   Set ie = CreateObject("InternetExplorer.Application")
   ie.navigate url

   'wait until the page loads
   Do While ie.ReadyState <> 4
      DoEvents
   Loop
   ie.Visible = True
   
   With ie.document
      'input name="Email" id="Email" size="18" value="" class="gaia le val" type="text"
      .GetElementById("Email").Value = user
      
       'input name="Passwd" id="Passwd" size="18" class="gaia le val" type="password"
       .GetElementById("Passwd").Value = pwd
       
       'input class="gaia le button" name="signIn" id="signIn" value="Sign in" type="submit"
       .GetElementById("signIn").Click
   End With
End Sub
 
Upvote 0
Rather than using GetElementById try using GetElementByName.

Then, using the, "names", in the html code in post #1 change the Main() procedure to:

Rich (BB code):
Sub main()
   Dim ie As Object
   
   Set ie = CreateObject("InternetExplorer.Application")
   ie.navigate URL


   'wait until the page loads
   Do While ie.ReadyState <> 4
      DoEvents
   Loop
   ie.Visible = True
   
   With ie.document
      'input name="Email" id="Email" size="18" value="" class="gaia le val" type="text"
      .GetElementByName("login_name").Value = user
      
       'input name="Passwd" id="Passwd" size="18" class="gaia le val" type="password"
       .GetElementByName("login_password").Value = pwd
       
       'input class="gaia le button" name="signIn" id="signIn" value="Sign in" type="submit"
       .GetElementByName("enter").Click
   End With
End Sub
 
Upvote 0
Thank you for the help sir but

I am getting the following error
run time error
I get Automation Error
The Object Invoked has disconnected from its clients
it opens the page but again dosnt do anything, on my login page when you look at it it is a simple user name pass and submit button
but in the HTML there are lots of craps involved would you please look at it and see if you catch anythign that i don't ?
I would appriciate you help. Thanks again here is my code i used that you mentioned and here is the entire HTML

Rich (BB code):
Private Sub CommandButton1_Click()
Const url = "mylink"
Const user = "myid"
Const pwd = "mypass"

   Dim ie As Object
   
   Set ie = CreateObject("InternetExplorer.Application")
   ie.Navigate url

   'wait until the page loads
   Do While ie.ReadyState <> 4
      DoEvents
   Loop
   ie.Visible = True
   
   With ie.Document
      'input name="Email" id="Email" size="18" value="" class="gaia le val" type="text"
      .GetElementByName("login_name").Value = user
      
       'input name="Passwd" id="Passwd" size="18" class="gaia le val" type="password"
       .GetElementByName("login_password").Value = pwd
       
       'input class="gaia le button" name="signIn" id="signIn" value="Sign in" type="submit"
       .GetElementByName("enter").Click
   End With
End Sub

' here is the html all the way to the buttom
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  
    ****** name="keywords" content="favicon, create, icon, favicon.ico, web, page, generate, bookmark, favorite, make, logo, site, internet, explorer, mozilla, firefox, convert, picture, ico, gif, jpeg, png, bmp, jpg, address, bar, ie" />
    <LINK rel="shortcut icon" type=image/x-icon href="favicon.ico">
    
    ******** language="javascript" src="/enovia/common/scripts/emxUIConstants.js">*********>
    ******** language="javascript" src="/enovia/common/scripts/emxUIModal.js">*********>
    <LINK rel=stylesheet type=text/css href="/enovia/common/styles/emxUIDefault.css">
    <LINK rel=stylesheet type=text/css href="/enovia/common/styles/emxUILogin.css">
    
 
    ******** ********************>
 
     function handle******() {
 
        //display the login form (only happens if JavaScript is enabled)
      if (isNS4) {
      setTimeout("void(0)",10);
        document.layers['layerLogin'].visibility = "show";
      } else if (isIE) {
        document.all['divLogin'].style.visibility = "visible";
      } else if (isMoz || isChrome || isKHTML) {
        document.getElementById('divLogin').style.visibility = "visible";
      }
 
        
        var bBreakOut = true;
        
 
        //if necessary, break out of the frame
        if (bBreakOut)
            breakout_of_frame();
     }
 
     function breakout_of_frame()
     {
 
      //check if there is an opener obj.
      //if so set it's location to this pages location and then close window
      //this should close all popup windows if opened in a chain
      if ((window.opener != null) && (window.opener != "undefined")){
        try
        {
            var protocol = ******************.protocol;
            var host = ******************.hostname;
            var port = ******************.port;
 
            var openerProtocol = window.opener.******************.protocol;
            var openerHostName = window.opener.******************.hostname;
            var openerPort = window.opener.******************.port;
 
            if ((protocol == openerProtocol) && (host == openerHostName) && (port == openerPort)){
                window.opener.location = ******************.href;
                window.close();
            }
        } catch(e){
 
        }
      }
 
         if (top.location != location) {
           top.location.href = ******************.href ;
         }
 
        //get reference to form
        var objForm = (isNS4 ? document.layers['layerLogin'].document.loginForm : document.loginForm);
 
         objForm.login_name.focus();
      }
 
      function mxSubmit (){
        //get reference to form
        var objForm = (isNS4 ? document.layers['layerLogin'].document.loginForm : document.loginForm);
        //Validate for a Username and Password entry
        if ((objForm.login_name.value == "")){
          alert("Please enter a Username.");
          objForm.login_name.focus();
        } else {
          objForm.action = "/enovia/servlet/login";
          objForm.submit();
        }
      }
 
    function doLoad() {
            if (isNS4) {
                    document.layers['divLogin'].visibility = "show";
            } else if (isIE) {
                    document.all['tableLogin'].style.visibility = "visible";
            } else if (isMoz || isChrome) {
                    document.getElementById('tableLogin').style.visibility = "visible";
            }
    }
 
    //call function close all windows
    closeAllChildWindows();
    *********>

 

 
<NOSCRIPT></NOSCRIPT>
 
 

    
        

        
            <FORM method=post name=loginForm>
                
<INPUT size=30 type=text name=login_name>
<INPUT size=30 type=password name=login_password AUTOCOMPLETE="off">
<INPUT class=button value=Login type=button name=enter *******="mxSubmit()"> <!--Code Added By Manoj for Change CHG000000029430 (Automated Account Creattion and Password Reset Utility) on 7/31/2009 - Start--> Forgot your password ? Reset Password Request New Account ? Click here Need Help For Account ? Click Here <!--Code Added By Manoj for Change CHG000000029430 (Automated Account Creattion and Password Reset Utility) on 7/31/2009 End-->
<TBODY> [TD="class: label"]Username[/TD] [TD="class: label"]Password[/TD] </TBODY>
</FORM> <!-- /.form-content --> <!-- /#divLoginImage --> <!--© Dassault Systèmes, 1993 – 2011. All rights reserved. --> <!-- /#divLogin --> ******** language="Javascript"> <!-- //include code here //write html to page with document.write //so we will only show content to javascript enabled browsers //--> *********> ******** language="JavaScript"> //get pointer to the form var objForm = (isNS4 ? document.layers['layerLogin'].document.loginForm : document.loginForm); // set default methods for events objForm.login_name.onkeypress = submitFunction; objForm.login_password.onkeypress = submitFunction; // check if EnterKey is pressed function submitFunction(e) { if (!isIE) Key = e.which; else Key = window.event.keyCode; if (Key == 13) mxSubmit(); else return; } // Manoj Self Service Password Reset Functionality - Starts function showEmployeeCodeFormAlert() { var strLoginUserName = objForm.login_name.value; if((strLoginUserName =="")||(strLoginUserName ==null)) { alert("Please Enter your User Name and then Reset Your Password"); } else { var strURL = "eaton_ResetPasswordUtilityFS.jsp?"; strURL += "&strLoginUserName="+strLoginUserName; var width = 800; var height = 300; var left = parseInt((screen.availWidth/2) - (width/2)); var top = parseInt((screen.availHeight/2) - (height/2)); var strFeatures = "menubar=no,titlebar=yes,width=500,height=350,resizable=no,scrollbars=no,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top; mywindow = ************(strURL,"",strFeatures); } } // Manoj Self Service Password Reset Functionality - Ends //Added this function for auto account creation function showCreateNewUserForm() { var strURL = "_CreateNewAccount.jsp?"; var width = 700; var height = 900; var left = parseInt((screen.availWidth/2) - (width/2)); var top = parseInt((screen.availHeight/2) - (height/2)); var strFeatures = "menubar=no,titlebar=yes,width=700,height=700,resizable=yes,scrollbars=no,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top; mywindow=************(strURL,"",strFeatures); }
 
Last edited:
Upvote 0
The code you posted is Javascript and doesn't provide anything which will help us. What we need is the "Name" or "ID" of the control.

If you find the "Name" use GetElementByName.
If you find the "ID", use GetElementById.

Navigate to the webpage as you would normally.
Right click the control.
Select Inspect Element (Chrome and ie - newer versions)
Names
Look for the "Name" assigned to the control.
Copy and paste the Names" in the highlighted code here:

Rich (BB code):
   With ie.Document
      .GetElementByName("login_name").Value = user
      .GetElementByName("login_password").Value = pwd
      .GetElementByName("enter").Click
   End With

Repeat for each control/button.

[edit]
This is pretty much the extent of the help I can provide without the url to the website, I'm afraid.
 
Last edited:
Upvote 0
Thank you for all the help sir, here is what the element inspection is gicing me looks like exactly what i found
Code:
<INPUT size=30 type=text name=login_name>
<INPUT size=30 type=password name=login_password AUTOCOMPLETE="off">
<INPUT class=button value=Login type=button name=enter *******="mxSubmit()">

input name="login_name" type="text" size="30"/
input name="login_password" type="password" size="30" AUTOCOMPLETE="off"/
input name="enter" class="button" *******="mxSubmit()" type="button" value="Login"/
so i dont know why its not working

The link that i don't provide is becasue its a internal server so the link won't work outside of the company
 
Upvote 0
I don't see why that shouldn't work. The "names" are correct.
Let's try a using ie.Document.All.Item("ItemName")

Rich (BB code):
Private Sub Main()
   Dim ie As Object
   
   Set ie = CreateObject("InternetExplorer.Application")
   With ie
      .navigate url
      Do While .Busy: DoEvents: Loop
      Do While .ReadyState <> 4: DoEvents: Loop
   End With
   
   With ie.document
      .all.Item("login_name").Value = user
      .all.Item("login_password").Value = pwd
      .all.Item("enter").Click
   End With
   
   ie.Visible = True


   Set ie = Nothing
End Sub

I have added another line to check the "Busy" state, but you shouldn't really need that; I normally only use this when I click webpage links via code.
 
Upvote 0
Thank you sir for all the help... its not working my URL end with emxLogin.jsp could it be because of JSP ?
 
Upvote 0

Forum statistics

Threads
1,223,713
Messages
6,174,043
Members
452,542
Latest member
Bricklin

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