Remove Controls From Excel Userform With VBIDE

江枫思渺然 提交于 2019-12-23 02:41:11

问题


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:


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



来源:https://stackoverflow.com/questions/35388423/remove-controls-from-excel-userform-with-vbide

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!