【问题标题】:How to manipulate Controls in a separate UserForm?如何在单独的用户窗体中操作控件?
【发布时间】:2019-11-10 09:41:49
【问题描述】:

我有两种形式:一种是创造性地命名为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

【问题讨论】:

    标签: excel vba forms controls


    【解决方案1】:

    用户表单是 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
    

    【讨论】:

    • 热狗,这很简单。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多