首页 文章

Userform组合框列表项将用户表单值保存为VBA Excel中的变体

提问于
浏览
0

我是第一次使用Excel用户表单,我遇到了一些麻烦 . 基本上,我想向我的用户询问三个值,然后将这些值保存为我的vba代码中的变体以供稍后使用 . 我最初设置我的VBA代码以使用三个单独的输入框来获取这三个值,但我发现拼写错误经常发生 . 相反,我希望用户只从值列表中选择 .

这是盒子的样子:

enter image description here

我只想在那里有两个组合框,每个都有两个选项,它们将始终是相同的选项,所以我不想把它们放在工作表的列表中,我希望它成为VBA代码的一部分 . 我的userform名为UserFormPYBTMT,组合框名为cboxlBT和cboxlMT,文本框为tbxxlPY . 这是我尝试过的:

Public Sub UserFormPYBTMT_Initialize()

'fill combobox for BT
    userformPYBTMT.cboxlBT.AddItem ("BTChoice1")
    userformPYBTMT.cboxlBT.AddItem ("BTChoice2")

'fill combobox for MT
    userformPYBTMT.cboxlMT.AddItem ("MTChoice1")
    userformPYBTMT.cboxlMT.AddItem ("MTChoice2")

End Sub

---------------------

Public Sub btnxlOK_Click()

End Sub

显然我也有OK按钮(我没有编写任何代码),此时我希望VBA将组合框值保存为我的变体并关闭userform . 我想要使用这些值的宏看起来像这样:

Sub SATV5()

Dim IBPYSAT As Variant
Dim IBMTSAT As Variant
Dim IBBTSAT As Variant

'Show the user form where we get the inputs for PY, MT, BT
userformPYBTMT.Show    

IBPYSAT = userformPYBTMT.tbxxlPY.Value
IBMTSAT = userformPYBTMT.cboxlMT.Value
IBBTSAT = userformPYBTMT.cboxlBT.Value

如果对某些用户形态和组合框有所了解的人可以给我一些指示,我将非常感激 . 谢谢 .

1 回答

  • 0

    您应该将变量声明为公共变量,并且应该使用userform而不是关闭它 . 见下面的例子:

    Public IBPYSAT As String, IBMTSAT As String, IBBTSAT As String
    
    Private Sub btnxlOK_Click()
    
    'Show the user form where we get the inputs for PY, MT, BT
    
    IBPYSAT = userformPYBTMT.tbxxlPY.Value
    IBMTSAT = userformPYBTMT.cboxlMT.Value
    IBBTSAT = userformPYBTMT.cboxlBT.Value
    
    userformPYBTMT.Hide
    
    Call MyMacroAfterClosingUserform
    
    End Sub
    
    Sub MyMacroAfterClosingUserform()
        MsgBox IBPYSAT & " is my Textbox value and " & IBMTSAT & " and " & IBBTSAT & " are my combobox values!"
        Unload userformPYBTMT 'now you can close userform after you are done with the variables!
    End Sub
    

相关问题