首页 > 解决方案 > 用户表单关闭时拉取选项按钮值

问题描述

我环顾四周寻找答案,但我看到的所有内容都有一个工作表上的选项按钮,而不是像我正在尝试做的用户表单。

快速运行:用户单击工作表上的按钮以将信息添加到列表中,但需要选择要添加到的列表。我有一个用户表单弹出选项按钮来选择他们想要添加到哪个。

问题是,当我回到我的代码时,我似乎无法获得按钮的值。我猜当我卸载用户表单时,所有变量和对象都被清理了,所以我想将一个值保存到一个全局变量中,但是用户表单的范围和代码的范围似乎并没有相互联系其他。

关于如何将选项按钮的值从用户表单中提取到我的模块代码中的任何想法?

我尝试了这些不同的变化:

    Not OptionButton1 Is Empty

    If UserForm1.OptionButton2 = True

    If UserForm1.OptionButton3.Value = True

标签: vbaexcel

解决方案


不要从其代码中卸载用户窗体,因此使用Me.Hide而不是Unload Me

这样,一旦在您的代码中(调用用户表单),您仍然可以访问用户表单成员

所以你的主要代码可能看起来像

Sub main()

    With UserForm1 ' load the userform
        .Show ' show the useform

        MsgBox .OptionButton1 ' <-- you still have access to Userform1 members
        MsgBox .OptionButton2
        MsgBox .OptionButton3
    End With
    Unload UserForm1 ' unload userform1

End Sub

而您退出的用户表单代码如下所示:

Private Sub CommandButton1_Click()
    Me.Hide ' just hide the userform, but still keep it "alive"
End Sub

推荐阅读