Excel VBA:IF ComboBox.Value 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25440637/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA: IF ComboBox.Value statement
提问by kolis29
Hi I have this ComboBox and I would like to do some command if the combox value says for example Paris
嗨,我有这个 ComboBox,如果组合框的值是巴黎,我想做一些命令
Private Sub Workbook_open()
With Sheet1.ComboBox1
.AddItem "Paris"
.AddItem "New York"
.AddItem "London"
End With
If Me.ComboBox1.Value = "Paris" Then
Range("A1").Value = 5
End If
End Sub
Any help? Thank you
有什么帮助吗?谢谢
回答by smagnan
Actually, your code is correct, but your condition will be called only when your workbook will be opened (WorkBook_open()) ...
实际上,您的代码是正确的,但是只有在打开工作簿时才会调用您的条件 ( WorkBook_open()) ...
This code:
这段代码:
If Me.ComboBox1.Value = "Paris" Then
     Range("A1").Value = 5
End If
should be in an other procedure.
应该在另一个程序中。
Ex:If you want A1to change when you select an item you can do:
例如:如果您想A1在选择项目时进行更改,您可以执行以下操作:
Private Sub Workbook_open()
    With Sheet1.ComboBox1
        .AddItem "Paris"
        .AddItem "New York"
        .AddItem "London"
    End With
End Sub
Private Sub ComboBox1_Change()
    If Me.ComboBox1.Value = "Paris" Then
        Range("A1").Value = 5
    End If
End Sub
Actually ComboBox1_Changeis called every time ComboBox1value changes (pretty obvious)
实际上ComboBox1_Change每次ComboBox1值变化时都会调用(很明显)
NOTE:This code is tested and works for me, but there are other ways to do, like adding a commandButtonand checking the condition only when this button is clicked.
注意:此代码经过测试并适用于我,但还有其他方法可以做,例如添加 acommandButton并仅在单击此按钮时检查条件。

