【问题标题】:Is there any limitation for IF condition while using "OR" in vb?在 vb 中使用“OR”时,IF 条件是否有任何限制?
【发布时间】:2012-02-27 22:51:05
【问题描述】:

在我的代码中,我想使用 if 条件。我想在其中使用“或”大约 18 次。 喜欢例如

If a="something" or a="something" or a="something" or.........(up to 18 times)... then
  'do nothing
else
  'do action
end if

[注意:a 的值在 For 循环 中每次都在变化] 所以我只想问在有限的时间内使用 OR 是否有任何限制。 或者有没有其他更好的方法来做同样的事情。

谢谢

【问题讨论】:

  • 我遇到了同样的问题。在两个“和”之后,我得到了属性或方法错误。在我的循环 for 循环中将 Case 用于我的 10 个 条件之后,它起作用了。

标签: vba vb6 vbscript


【解决方案1】:

据我所知,这种方式使用OR没有限制。

不过,您可以考虑使用其他编码方式。

使用 Not 否定条件

首先,如果您在第一种情况下do nothing,则考虑使用Not 语句

If Not True Then
'do somethin
'no else
End If

考虑使用 Select Case

其次,如果您检查的是同一个变量,您可以考虑使用Select Case,但如果您只有一种情况,这似乎不适合您的情况。

尝试使用搜索

最终,如果您正在检查字符串,您最好使用 在数组中搜索(如果您在 Excel 中,则使用 Application.Match.Contains)或 在字符串中 使用Instr

使用集合或字典

[编辑] 另一个很好的处理方法是使用 VBA 的 Dictionary Structure 并检查 a 是否存在(有关一些信息,请参阅 MSDN)。

【讨论】:

  • 在我看来像是 Select Case 的候选者...a 是反复测试的变量。
  • @tcarvin:这就是我指出它存在的原因。然而,Select Case 在您有许多 Else If(即几个案例)而您在这里只有一个结果时非常有用,所以我会考虑使用其他解决方案(数组、字典...)。
  • 对于字符串比较,Like 运算符甚至正则表达式匹配可能是更简洁的选择,具体取决于所测试的内容。
  • 一般来说:如果你必须要求一个系统的限制,那么可能有更好的方法来做到这一点。
【解决方案2】:

这个答案只是我对 JMay 的阐述,完全归功于他。我认为他的问题中针对“某事”的原始海报不同,a 是循环变量。

For each a in MyList

   Select Case a
   Case "something", "something2", "something3", "something4", "something5", _
        "something6", "something7", "something8", "something9", "something10", _
        "something11", "something12", "something13", "something14", "something15", _
        "something16", "something17", "something18"

       'DO NOTHING

   Case Else

       'do-something code goes here
       ' and here
       ' and here
       ' and here
   End Select

Next a

【讨论】:

  • 做得很好。我对Case 语法不够熟悉,我不记得您可以将逗号用作OR 运算符:)
  • @JMax 好吧,那么您将更加欣赏Select Case True 构造。也可用于short circuit evalution
猜你喜欢
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 2015-11-09
  • 2012-07-24
  • 2014-05-08
相关资源
最近更新 更多