excel - 用户表单中的组合框问题
问题描述
我在用户表单中工作,并且正在对组合框进行编码。我在我的组合框中放置了一个下拉列表.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
解决方案
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 中,您可以使用AndAlso
andOrElse
操作符,它确实如此。短路逻辑运算符的结果是,一旦知道结果,评估布尔表达式就可以退出:
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
推荐阅读
- python - 使用 CNN 微调预训练的 BERT。如何禁用遮罩
- c - 如何使用 C 中的 ADT 制作链表的副本?
- vlc - 如何解决我的 vlc 媒体问题,它显示 MRL 文件格式问题
- vba - 没有ID的VBA单击按钮
- python - Python - Find Coordinates Relative to Screen
- concurrency - 如何解决 ClickHouse 死锁?
- javascript - Navigation Menu CSS not linking
- unity3d - Unity 中的主摄像头错误:“此摄像头使用的渲染器不支持摄像头堆叠。只有基本摄像头会渲染。”
- swift - 链接显示为红色而不是蓝色?
- json - Serialize a Map
> using gson Grails view