Home » excel » excel – Access VBA Userform Controls without Form instance

excel – Access VBA Userform Controls without Form instance

Posted by: admin April 23, 2020 Leave a comment

Questions:

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 example:

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

First executes 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 frmConfig.Form_Initialize())?

Any help much appreciated!

How to&Answers:

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

IMP:

  1. Set reference to Microsoft Visual Basic For Applications Extensibility
  2. In Excel options, set “Trust Access To the VBA project Object Model”

Screen Shot

enter image description here

FOLLOWUP

Since this is a one time thing, do this

  1. Open VBA Project
  2. Press CTRL + F
  3. Do as shown in the screenshot below and then run the code.
  4. Close the file without saving once you have got what you need

enter image description here