模仿“IN”操作员
如何才能实现:
if X in (1,2,3) then
而不是:
if x=1 or x=2 or x=3 then
换句话说,如何才能最好地模仿 Excel 的 VBA 中的 IN
运算符?
How can one achieve:
if X in (1,2,3) then
instead of:
if x=1 or x=2 or x=3 then
In other words, how can one best imitate the IN
operator in VBA for excel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我认为没有一个非常优雅的解决方案。
但是,您可以尝试:
或者您可以编写自己的函数:
I don't think there is a very elegant solution.
However, you could try:
or you could write your own function:
您还可以尝试使用 CASE 语句代替 IF
You could also try the CASE statement instead of IF
最快的方法:
这是一种比其他答案任何更快、更紧凑的方法,并且适用于数字或文本值:
示例:
将
IsIn
与数值一起使用:将
IsIn
与字符串值一起使用:速度比较:
为了比较速度,我从接受的答案运行了测试 100,000 次:
0.406 秒(最快)
此函数(使用 InStr):1.828 秒(慢 450%)
已接受 使用“ISIN”函数回答1.799 秒(慢 440%)
用 freeVBcode 中的“IsInArray”回答0.838 秒(慢 206%)
使用修改后的“IsInArray”函数回答我没有包含更长的答案< /a> 使用 SELECT..CASE ,因为与“
if x=1 or x=2 or x=3 那么
”。Fastest Method:
Here's a method much faster and more compact than any of the other answers, and works with numeric or text values:
Examples:
Use
IsIn
with a numeric value:Use
IsIn
with a string value:Speed Comparison:
To compare speed I ran the test from the accepted answer 100,000 times:
0.406 sec (FASTEST)
This Function (using InStr):1.828 sec (450% slower)
Accepted Answer with the "ISIN" function1.799 sec (440% slower)
Answer with the "IsInArray" from freeVBcode0.838 sec (206% slower)
Answer with modified "IsInArray" functionI didn't include the much longer answer that uses
SELECT..CASE
since the OP's goal was presumably to simplify and shorten the task compared to "if x=1 or x=2 or x=3 then
".你试过吗
did you try
据我所知,没有一个。
我通常使用自制的 InArray() 函数,例如 http://www 中的函数.freevbcode.com/ShowCode.asp?ID=1675
您还可以制作一个迭代数组而不是连接的版本(如果这更适合您的数据类型)。
There's none that I'm aware of.
I usually use a home-brewed InArray() function like the one at http://www.freevbcode.com/ShowCode.asp?ID=1675
You could also make a version that iterates through the array instead of concatenating, if that is more appropriate to your data type.
如果不编写自己的函数,它就无法工作。请注意,@Kredns 接受的解决方案可能无法按预期适用于所有类型的对象,因为它们被强制为字符串(这也可能引发类型不匹配错误)。
该解决方案应该(希望)处理所有类型的数据(至少在 Excel 365 中,不确定早期版本):
It doesn't work without writing your own function. Be aware that the accepted solution by @Kredns may not work as expected for all types of objects since they are coerced to strings (which also may raise Type Mismatch errors).
This solution should (hopefully) handle all types of data (at least in Excel 365, not sure about earlier versions):
我现在写了...
I wrote it now...