英文:
Understanding And/Or logic VBA
问题
第二个 If
语句在用户未输入正确的水果时显示消息,然而第一个语句根本不起作用。
以下是第一个 If
语句的修正:
If Item.Value <> "Peach" And Item.Value <> "Banana" And Item.Value <> "Mango" Then
MsgBox "水果不可用"
End If
第一个 If
语句应该使用 "And" 连接条件,而不是 "Or",以便要求用户输入不是 "Peach"、"Banana" 和 "Mango" 中的所有水果才会显示消息。
英文:
I'm so confused about why the second If
statement works but the first one does not.
The actual result I want is if the user does not enter Peach or Banana or Mango then show the message.
The Or
's in the sentence above makes the most sense. However, if I said "if the user does not enter Peach and Banana and Mango" then show the message - It sounds like you would need to enter all three fruits to show the message which is not the result I'm looking for. But! It's the one that works.
The second If
statement shows the message if none of the correct fruit is entered however, the first statement does not work at all.
Please help clarify.
Column A | Column B |
---|---|
Cell 1 | Apple |
Cell 2 | Orange |
If Item.Value <> "Peach" or Item.Value <> "Banana" or Item.Value <> "Mango" Then
MsgBox "Fruit Not Available"
End If
If Item.Value <> "Peach" And Item.Value <> "Banana" And Item.Value <> "Mango" Then
MsgBox "Fruit Not Available"
End If
I tried both statements but only the second one works and I'm confused why that is.
答案1
得分: 0
VBA将评估每个比较是否为真/假。
假设Item.Value = "Peach",那么我们得到:
false = Item.Value <> "Peach"
true = Item.Value <> "Banana"
true = Item.Value <> "Mango"
将这些放在第一个OR条件中,你会得到:
true = false or true or true
无论值是不是水果中的任何一个,它都将始终返回true,而不会起作用。
将这些放在第二个AND条件中,你会得到:
false = false AND true AND true
这是当一个水果匹配时。如果Item.Value = "Apple",你会得到:
true = true AND true AND true
对于你来说,这将导致"第二个语句有效",但实际上它们两个都是正确的,只是第一个对你没有意义。
英文:
VBA will evaluate each of the comparisons to true/false
Lets assume the Item.Value = "Peach"
so we get:
false = Item.Value <> "Peach"
true = Item.Value <> "Banana"
true = Item.Value <> "Mango"
Having this in the first or will give you:
true = false or true or true
Regardsless if the value is any of the fruits or not, it will give you always true and will not work.
Having this in the second AND will give you:
false = false AND true AND true
This is when one fruit is a match. If Item.Value = "Apple" you will get:
true = true AND true AND true
for you this results in "the second statement works" where as they both work correctly but the first has no value for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论