用户表单中的组合框问题

时间:2019-01-14 20:05:15

标签: excel vba userform

我正在使用用户窗体,并且正在组合框上进行编码。我使用.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

1 个答案:

答案 0 :(得分: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,如果该代码位于名为Unload AccountsVbaPro的表单的代码后面,则AccountsVbaPro也是如此。


1 VBA中不存在短路运算符。例如在VB.NET中,您必须使用AndAlsoOrElse运算符。 短路逻辑运算符的结果是,一旦知道布尔表达式的结果,就可以对其求救:

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

vs

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