首页 > 解决方案 > 如何在单独的用户窗体中操作控件?

问题描述

我有两种形式:一种是创造性地命名UserForm1我所有的魔法发生的SettingsForm地方,另一种是用户可以调整一些设置的地方。UserForm1可以打开SettingsForm并在将来初始化时加载任何保存的设置。

我遇到的问题是将当前打开UserForm1的设置更新为新选择的设置,当它们保存在SettingsForm. 其中一个设置是一组选项按钮中的默认选择。

我尝试通过更改Me.Controls为来修改我在其他地方使用的循环来处理选项组[Forms]![exportForm].Controls,但这会引发错误。我以前从未以其他形式引用过控件,所以我不确定我在做什么(阅读:我完全一无所知)。(defBGU是前面代码中定义的字符串)

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

标签: excelvbaformscontrols

解决方案


用户窗体是 VBA 中的一个类,您可以(并且应该)使用变量来访问它。通常,您在代码中编写类似

UserForm1.Show

这将创建一个所谓的表单默认实例。但你也可以这样做

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

您可以使用此变量并访问它的所有成员(Me如果您在表单代码中,则无非是对实例本身的引用)。

所以你的 UserForm1 中的部分代码可能看起来像

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

推荐阅读