Uncheck a checkbox in IE

11,715

Here is the code that allows to make a common test if we can uncheck the checkbox:

Public Sub TestIE()
    Dim IE As Object
    Dim Element As Object
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.Navigate "about:blank"
    IE.document.write "<html><body><input name=""chkbx_name"" class=""chkbx_cls"" id=""chkbx"" type=""checkbox"" checked=""checked""></body></html>"
    IE.document.parentWindow.alert "Verify checkbox is checked"
    Set Element = IE.document.getElementById("chkbx")
    Element.Checked = False
    IE.document.parentWindow.alert "Verify checkbox is unchecked"
    IE.Quit
End Sub

For me it works as expected: shows checked checkbox and first alert, then unchecks it and shows second alert. If your webpage is working in other way then it pays to inspect the checkbox on your webpage for some onclick or onchange event handler via developer tools. In IE, press F12, click DOM Explorer, select the checkbox in HTML code, click Events tab. If there is any event handler then you have to clarify if it modifies the state of the checkbox or not (immediately after your VBA does).

Share:
11,715
Aditya Guru
Author by

Aditya Guru

Updated on June 04, 2022

Comments

  • Aditya Guru
    Aditya Guru almost 2 years

    I am trying to uncheck an already checked checkbox on a webpage using excel VBA.

    HTML code:

    <div class="mycheckbox checked">
    <label class="mycheckbox1 checked" data-initialize="checkbox">
        <input name=<name> class=<class> id=<id> type="checkbox" checked="checked"></input></label></div>
    

    VBA code stub:

        Public Sub uncheck(IE As Object)
        Dim Element As Object
            With IE.Document
                Set Element = .getElementById(<id>)
                Element.Checked = False
                Element.defaultChecked = False        
            End With
        End Sub
    

    This does not work out as desired as HTML code changes to -

    <div class="mycheckbox checked">
    <label class="mycheckbox1 checked" data-initialize="checkbox">
        <input name=<name> class=<class> id=<id> type="checkbox" checked=""></input></label></div>
    

    The checkbox is not unchecked as there is still the checked attribute

    Even tried the below(Clicking on the checkbox). It does not do anything at all -

        Public Sub uncheck(IE As Object)
        Dim Element As Object
            With IE.Document
                Set Element = .getElementById(<id>)
                Element.Click
            End With
        End Sub
    

    Any suggestions? Or may I know why my approach not working?