Tock
Tock

Reputation: 61

How to manipulate Controls in a separate UserForm?

I have two forms: One, the creatively named UserForm1 where all my magic happens, and two, SettingsForm where the user can adjust some settings. UserForm1 can open SettingsForm and will load any saved settings when initialized in the future.

The issue I'm running into is updating the currently-open UserForm1 to the newly chosen settings when they're saved over in SettingsForm. One of those settings is the default selection in a group of option buttons.

I've tried modifying the loop I use elsewhere to deal with option groups, by changing Me.Controls to [Forms]![exportForm].Controls, but that's throwing an error. I've never referenced controls in another form before, so I'm not really sure what I'm doing (read: I'm completely clueless). (defBGU is a string defined in previous code)

Dim opt As Control
For Each opt In [Forms]![exportForm].Controls
    If TypeName(opt) = "OptionButton" Then
        If opt.Name = defBGU Then
            opt.Value = True
        End If
    End If
Next

Upvotes: 0

Views: 141

Answers (1)

FunThomas
FunThomas

Reputation: 29592

A userform is a class in VBA, and you can (and should) use a variable to access it. Usually, you write in your code something like

UserForm1.Show

and that will create a so called default instance of the form. But you can also do

Dim frm as UserForm1
set frm = new UserForm1
frm.show

You can use this variable and access all it's members (Me is nothing else than a reference to the instance itself if you are within the form code).

So part of the code in your UserForm1 could look like

Dim frmSettings As SettingsForm    ' Declare a variable for the setting form

Private Sub CommandButton1_Click()
    ' Create a new instance of the setting form
    If frmSettings Is Nothing Then Set frmSettings = New SettingsForm

    ' Do some manipulations and show it
    With frmSettings
        .Caption = "Greetings from " & Me.Name
        .Label1.Caption = "I was set by " & Me.Name
        .TextBox1.Text = "Me too..."
        .Show
    End With
End Sub

Upvotes: 1

Related Questions