VB。如果有多个或里面

时间:2016-01-19 14:23:42

标签: excel vba excel-vba

我想把这个If放在一个宏中,但它总是给我一个错误。我不知道“Or”是否正确使用。

 Dim SMAT As String
 SMAT = "blahblahblah"
    (...)  
 If Cells(h + 2, 24) <> SMAT Or SMBE Or SMES Or SMFR Or SMGB Or SMGR Or SMRO1 Or SMRO2 Or SMRO3 Or SMDE Then
        C(j) = Cells(h + 2, 5)

2 个答案:

答案 0 :(得分:4)

改为使用Select Case块:

Select Case Cells(H + 2, 24).Value
    Case SMAT, SMBE, SMES, SMFR, SMGB, SMGR, SMR01, SMR02, SMR03, SMDE
    Case Else
        c(j) = Cells(H + 2, 5).Value
End Select

或者使用Evaluate()的另一种方式,只是为了变化*:

varConditions = Array(SMAT, SMBE, SMES, SMFR, SMGB, SMGR, SMR01, SMR02, SMR03, SMDE)

If Evaluate("ISERROR(MATCH(" & Cells(H + 2, 24).Value & ",{" & _
    Join(varConditions, ",") & "},0))") Then
        c(j) = Cells(H + 2, 5).Value
End If

*当数组包含数字时,此Evaluate方法将起作用 - 如果您使用的是字符串,则必须将每个字符串用其他引号括起来

答案 1 :(得分:2)

这是更正

Dim SMAT As String
SMAT = "blahblahblah"
'(...)
If Cells(H + 2, 24) <> SMAT Or _
   Cells(H + 2, 24) <> SMBE Or _
   Cells(H + 2, 24) <> SMES Or _
   Cells(H + 2, 24) <> SMFR Or _
   Cells(H + 2, 24) <> SMGB Or _
   Cells(H + 2, 24) <> SMGR Or _
   Cells(H + 2, 24) <> SMRO1 Or _
   Cells(H + 2, 24) <> SMRO2 Or _
   Cells(H + 2, 24) <> SMRO3 Or _
   Cells(H + 2, 24) <> SMDE Then
    c(j) = Cells(H + 2, 5)
End If

Or Operator (Visual Basic)

错误是因为你正试图&#34;谈论&#34;像人一样对VBA,但or不接受另一个or的参数。您需要告诉每个or的每个参数,以告知完整的logical test

firstCheck = a > b Or b > c
firstCheck = Logical_test Or Logical_test