Remove Dynamically Added Controls from Userform

calendar_today Asked Jan 6, 2015
thumb_up 7 upvotes
history Updated April 16, 2026

Question posted 2015 ยท +6 upvotes

I have an excel Userform with dynamically added checkboxes. I add the checkboxes early on with code that looks like this:

Set chkBox = Me.Controls.Add("Forms.Checkbox.1", "Checkbox" & i)

Later, I want to remove all of these checkboxes. I’m trying this code:

    Dim j As Integer
'Remove all dynamically updated checkboxes
For Each cont In Me.Controls
    For j = 1 To NumControls
    If cont.Name = "Checkbox" & j Then
        Me.Controls.Remove ("Checkbox" & j)
    End If
    Next j
Next cont

But am getting the following error message: Error MEssage

any help would be greatly appreciated.

Accepted answer +7 upvotes

A better approach may be to keep track of the controls you create (eg in a collection), and use that to remove them.

This way your code is not bound to the name format, and can be applied to other control types too.

Private cbxs As Collection

Private Sub UserForm_Initialize()
    Set cbxs = New Collection
End Sub

' Remove all dynamicly added Controls
Private Sub btnRemove_Click()
    Dim i As Long
    Do While cbxs.Count > 0
        Me.Controls.Remove cbxs.Item(1).Name
        cbxs.Remove 1
    Loop
End Sub


' Add some Controls, example for testing purposes
Private Sub btnAdd_Click()
    Dim i As Long
    Dim chkBox As Control
    For i = 1 To 10
        Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "SomeRandomName" & i)
        chkBox.Top = 40 + i * 20
        chkBox.Left = 20
        cbxs.Add chkBox, chkBox.Name  ' <-- populate tracking collection
    Next

    ' Demo that it works for other control types
    For i = 1 To 10
        Set chkBox = Me.Controls.Add("Forms.ListBox.1", "SomeOtherRandomName" & i)
        chkBox.Top = 40 + i * 20
        chkBox.Left = 60
        chkBox.Add chkBox, chkBox.Name
    Next

End Sub

Top excel-vba Q&A (6)

+7 upvotes ranks this answer #101 out of 136 excel-vba solutions on this site .