【问题标题】:Problems with comboboxes in a userform用户表单中的组合框问题
【发布时间】:2019-06-08 20:22:20
【问题描述】:

我在用户窗体中工作,并且正在对组合框进行编码。我使用.additem 在我的组合框中放置了一个下拉列表,每次用户按下列表中的一个项目时,都会出现一个消息框。

由于某种原因,我的第一个代码使消息框重新出现在组合框中的下一行,所以当按下第二行时,我有两个消息框而不是一个。

是因为and 函数吗?有没有其他方法可以做到这一点?

澄清一下,ComboBox1.ListIndex = 2(出现 2 个消息框,而我只需要我编码的那个)和 ComboBox1.ListIndex = 3(出现 3 个消息框而不是 1 个)。

If ComboBox1.ListIndex = 1 And Msgbox("Do you want to create a new company?", vbYesNo) = vbYes Then UserForm1.Show

If ComboBox1.ListIndex = 2 And Msgbox("Do you want to open the reports screen?", vbYesNo) = vbYes Then UserForm2.Show

If ComboBox1.ListIndex = 3 And Msgbox("Are you sure", vbYesNo) = vbYes Then Unload AccountsVbaPro

【问题讨论】:

    标签: excel vba userform


    【解决方案1】:

    And 运算符(不是函数)不会短路1,所以在为了评估布尔表达式结果是否为True,VBA 需要MsgBox 函数的结果...对于每个条件。

    'both foo and bar need to be evaluated to know whether DoSomething needs to run:
    If foo And Bar Then DoSomething
    

    使MsgBox 调用有条件 - 我建议使用Select Case 块,以避免每次都重复ComboBox1.ListIndex 成员访问:

    Select Case ComboBox1.ListIndex
       Case 1
           If Msgbox("Do you want to create a new company?", vbYesNo) = vbYes Then UserForm1.Show
       Case 2
           If Msgbox("Do you want to open the reports screen?", vbYesNo) = vbYes Then UserForm2.Show
       Case 3
           If Msgbox("Are you sure", vbYesNo) = vbYes Then Unload AccountsVbaPro
    End Select
    

    请注意,UserForm1.Show / UserForm2.Show 最终是 likely going to cause problems,如果该代码位于名为 AccountsVbaPro 的表单的代码隐藏中,Unload AccountsVbaPro 也是如此。


    1VBA 中不存在短路运算符。在例如VB.NET,您可以使用 AndAlsoOrElse 运算符,它们可以。 短路逻辑运算符的结果是,一旦知道结果,评估布尔表达式就可以退出:

    If True Or True Or False Then ' all operands need to be evaluated
    

    If True OrElse True OrElse False Then ' evaluation stops at the first True; 2nd & 3rd operands are skipped
    

    【讨论】:

    • 哇,这工作 Mathieu Guindon 谢谢你。我对编程完全陌生,所以我不知道你可以使用(选择案例)。至于注意 UserForm1.Show / UserForm2.Show 可能会产生问题,什么时候会出现这些问题?
    • 当你开始Newing 的时候。请参阅链接文章;-)
    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多