首页 > 解决方案 > 用户表单中的组合框问题

问题描述

我在用户表单中工作,并且正在对组合框进行编码。我在我的组合框中放置了一个下拉列表.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

标签: excelvbauserform

解决方案


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代码Unload AccountsVbaPro位于名为 的表单的代码隐藏中一样AccountsVbaPro


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

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

推荐阅读