I have a friend with a VBA project in Excel. This project has a lot of Forms that pop up and perform various functionality while the spreadsheet is being used. Some of them have complex
Form_Initialize methods that rely on other things already existing (this is not a problem when the project is used as expected).
We are trying to print out the names of every control on every form within the application. Our problem is that the
VBA.UserForms collection only contains forms that have already been instantiated, and we can’t instantiate all the forms without their
Form_Initialize methods executing.
For Each f In VBA.UserForms Debug.Print f.Name Debug.Print "----------------------" For Each c In f.Controls Debug.Print c.Name Next c Next f
does nothing if no forms have been used/loaded. This code:
For Each c in frmConfig.Controls Debug.Print c.Name Next c
frmConfig.Form_Initialize(), then loops through the controls on the form printing their names. This crashes, as things that need to happen before this form is available have not happened.
Is it possible to get the names of the controls on a form WITHOUT instantiating the form (avoiding execution of
Any help much appreciated!
Is this what you are trying?
Option Explicit Sub FindObjects() Dim vbc As VBIDE.VBComponent Dim frm As Object Dim Ctrl As MSForms.Control For Each vbc In ThisWorkbook.VBProject.VBComponents If vbc.Type = vbext_ct_MSForm Then With VBA.UserForms On Error Resume Next Set frm = .Add(vbc.Name) Debug.Print "Found userform :" & vbc.Name If Err.Number = 0 Then For Each Ctrl In frm.Controls Debug.Print "Controls in Userform " & vbc.Name & _ " - " & Ctrl.Name Next Ctrl End If On Error Go To 0 End With End If Next vbc End Sub
- Set reference to Microsoft Visual Basic For Applications Extensibility
- In Excel options, set “Trust Access To the VBA project Object Model”
Since this is a one time thing, do this
- Open VBA Project
- Press CTRL + F
- Do as shown in the screenshot below and then run the code.
- Close the file without saving once you have got what you need