Search code examples
excelvbacheckboxuserformcommandbutton

VBA userform to execute selections only after hitting command button


I am having a hard time to make vba to execute my selection only after pressing the command button (The GO button in this case). Attached are the picture of the userform, which is not made by activeX control, and the code I am working on. Thanks!

Picture of Userform

Private Sub MR_Click()

If MR.Value = True Then
Rows(6).Delete
End If

End Sub

Private Sub PMS_Click()

If PMS.Value = True Then
Rows(7).Delete
End If

End Sub

Private Sub VOIDMR_Click()

If VOIDMR.Value = True Then
Rows(13).Delete
End If

End Sub

Private Sub VOIDPMS_Click()

If VOIDPMS.Value = True Then
Rows(14).Delete
End If

End Sub

Solution

  • Like this, using a "Go" button's _Click event procedure (presumably GO_Click(), but modify if needed) to check against each of the checkboxes and do the deletion accordingly.

    Private Sub GO_Click()
    If MR.Value = True Then
        Rows(6).Delete
    End If
    If PMS.Value = True Then
        Rows(7).Delete
    End If
    If VOIDMR.Value = True Then
        Rows(13).Delete
    End If
    If VOIDPMS.Value = True Then
        Rows(14).Delete
    End If
    End Sub
    'These event procedures won't do anything, and can be removed:
    Private Sub MR_Click()
    End Sub
    Private Sub PMS_Click()
    End Sub
    Private Sub VOIDMR_Click()
    End Sub
    Private Sub VOIDPMS_Click()
    End Sub
    

    The checkboxes' _Click event procedures are no longer needed.

    To note about the event procedures, they will fire whenever the event occurs. So for an checkbox with a _Click event, any time the user checks (or unchecks) _Click handler will execute.

    As noted, exercise caution when deleting elements from a collection, as this typically needs to be done in reverse order (when you delete row 6, row 7 becomes row 6, so if both MR and PMS are checked, what's in Row 7 initially will not be deleted). This may require some additional code change, but very simply it seems by just re-ordering the commands within GO_Click, should handle this:

    Private Sub GO_Click()
    If VOIDPMS.Value = True Then
        Rows(14).Delete
    End If
    If VOIDMR.Value = True Then
        Rows(13).Delete
    End If
    If PMS.Value = True Then
        Rows(7).Delete
    End If
    If MR.Value = True Then
        Rows(6).Delete
    End If
    
    End Sub