Remove Controls From Excel Userform With VBIDE

1.4k views Asked by At

I need to remove some controls from 75 Excel userforms. I got VBA code looping thorough the files and using the VBIDE, I got the code removed. However, haven't been able to get a handle on the controls.

Rather than wasting time with code I have tried, here are the object I have been using:

Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim CompItem As Object
Dim objVBFrm As UserForm

Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("frmSend")
Set CodeMod = VBComp.CodeModule
Set objVBFrm = VBComp.Designer

With objVBFrm
    .Controls.Remove chkNewCNV
End With

thanks all

1

There are 1 answers

2
user3598756 On

maybe I didn't get your exact goal, but what follows should help you get started at least

Sub RemoveControlsFromUserForm()
Dim VBP As VBIDE.VBProject
Dim VBC As VBIDE.VBComponent
Dim cntrls As Controls
Dim cntrl As Control

Set VBP = ActiveWorkbook.VBProject
For Each VBC In VBP.VBComponents
    With VBC
        If .Type = vbext_ct_MSForm And .Name = "UserForm1" Then
            Set cntrls = .Designer.Controls
            For Each cntrl In cntrls
                If TypeName(cntrl) = "CheckBox" Then
                    If cntrl.Name = "chkNewCNV" Then cntrls.Remove cntrl.Name
                End If
            Next cntrl
        End If
    End With
Next VBC

End Sub

just change component type (vbext_ct_MSForm) and name ("UserForm1") as well as control ones ("CheckBox", "chkNewCNV") as per your needs

as for the"Invalid forward reference" error, it could be the "frmSend" userform is loaded while you're attempting to change (delete) its controls. should that be the case, you must firts unload it (only hiding it wouldn't work) then act on it and finally load it. or it could be that you must run the removing logic sub before the removing control one or a mix of the two... and then there could still last some issues due to the actual timing of all those operations (unloading form, processing it and its controls/logic) having them unproperly (though involuntarily) interfere.

To get rid of those (and may be other!) possible side effects a plain solution could be simply hiding unwanted userform controls, and that you can do right in your code that loads the userform just before showing it. Or, if you "must" act programmatically, you can add those "hiding" code lines processing (instead of removing) the logic