vba IF 'AND' 和 'OR' 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8309817/
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
IF 'AND' and 'OR' Statements
提问by DevilWAH
My code is as follows:
我的代码如下:
If (InStr(1, "ALL", Itype) Or InStr(1, Uvar.Device, Itype) _
And (InStr(1, "ALL", Isec) Or InStr(1, Uvar.Sec, Isec)) _
And (InStr(1, "ALL", Idev) Or InStr(1, Uvar.Model, Idev)) Then Useline = "TRUE"
To expand on this a bit:
稍微扩展一下:
Itype is a long string, e.g. -
Itype 是一个长字符串,例如 -
Itype = All, Apple, Pear, Orange
Isec = dog, cat, duck
Idev = tree, flower, plant
Itype = All, Apple, Pear, Orange
Isec = dog, cat, duck
Idev = tree, flower, plant
Each UVar.x is a single word, e.g. -
每个 UVar.x 都是一个单词,例如 -
UVar.Device = Apple
UVar.Sec = Cat
UVar.Model = tree
UVar.Device = Apple
UVar.Sec = Cat
UVar.Model = tree
So, if Itype contains the string "All" or it contains the value of UVar.Device and Isec also contains the string "All" or it contains the value of UVar.Sec and IDev also contains the string "All" or it contains the value of UVar.Model
因此,如果 Itype 包含字符串“All”或包含 UVar.Device 的值且 Isec 也包含字符串“All”或包含 UVar.Sec 的值且 IDev 也包含字符串“All”或包含UVar.Model 的值
then I want to have the if statement = true
.
那么我想拥有if statement = true
.
My code above seems to return true whatever values are used, as long as at least one value criteria set matches.
我上面的代码似乎无论使用什么值都返回 true,只要至少有一个值标准集匹配。
Thus, do the strings IType, Idev and Isec each contain either the value "all" or a specific user defined value?
因此,字符串 IType、Idev 和 Isec 是否都包含值“all”或特定的用户定义值?
回答by Tom Juergens
Well, for one thing, your code doesn't compile - you either have to remove the opening parenthesis after the IF or add a matching closing parenthesis.
嗯,一方面,您的代码无法编译 - 您必须删除 IF 之后的左括号或添加匹配的右括号。
More importantly, though, you've got the order of the Instr() parameters mixed up. First is string to look IN, second is string to look FOR. That should solve it.
更重要的是,您已经混淆了 Instr() 参数的顺序。第一个是查找IN 的字符串,第二个是查找FOR 的字符串。那应该可以解决它。
PS: While Brettdj's answer is true, VBA will interpret the position 0 as false and any other as true, so that's not necessarily the issue.
PS:虽然 Brettdj 的答案是正确的,但 VBA 会将位置 0 解释为假,将任何其他位置解释为真,所以这不一定是问题所在。
回答by brettdj
(Updated: To fix order and to return a True Boolean variable)
(更新:修复顺序并返回一个真正的布尔变量)
InStr
returns a position, not True or False. So you could add both tests together to test for >0 as then at least one of the two paired conditions is true. Then test all 3 pairs, ie
InStr
返回一个位置,不是 True 或 False。因此,您可以将两个测试加在一起以测试 >0,因为至少两个配对条件之一为真。然后测试所有3对,即
Dim bVar As Boolean
bVar = (InStr(Itype, "ALL") + InStr(Itype, Uvar.Device)) > 0 _
And (InStr(Isec, "ALL") + InStr(Isec, Uvar.Sec)) > 0 _
And (InStr(Idev, "ALL") + InStr(Idev, Uvar.Model)) > 0