Remove Dynamically Added Controls from Userform
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 CollectionPrivate Sub UserForm_Initialize() Set cbxs = New CollectionEnd Sub' Remove all dynamicly added ControlsPrivate Sub btnRemove_Click() Dim i As Long Do While cbxs.Count > 0 Me.Controls.Remove cbxs.Item(1).Name cbxs.Remove 1 LoopEnd Sub' Add some Controls, example for testing purposesPrivate 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 cbxs.Add chkBox, chkBox.Name NextEnd Sub
if you already know the name of the controls, the type, and how many, why double loop ?
note that ONLY controls created at runtime can be removed.
'the following removes all controls created at runtimeDim i As LongOn Error Resume NextWith Me.Controls For i = .Count - 1 to 0 step -1 .Remove i Next iEnd WithErr.Clear: On Error GoTo 0
and for your case : 'if all naming are correct
Dim j&For j = 1 To NumControls Me.Controls.Remove "Checkbox" & jNext j