2

I want to put this If in a macro but it gives me an error all the time. I dont know if "Or" is used correctly or not.

 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
  • 2
    What is the code supposed to do? Do you want to check that Cells(h + 2, 24) is not equal to all of those SM* strings? If so, you'll need to repeat the test each time. If (Cells(h + 2, 24) <> SMAT) Or (Cells(h + 2, 24) <> SMBE) Or ... Parentheses help. Commented Jan 19, 2016 at 14:29
  • I still think they should be AND's not OR's but of course using 'like' operator was rubbish. Commented Jan 19, 2016 at 15:18

2 Answers 2

4

Use a Select Case block instead:

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

Or another way using Evaluate(), just for variety*:

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

* This Evaluate method will work when the array contains numbers - if you are using strings you would have to wrap each string in additional quotation marks

Sign up to request clarification or add additional context in comments.

3 Comments

Plus 1 for the SELECT CASE.
the Select Case block does exactly the opposite haha thanks anyway for your help
@PedroLastra sorry, missed a line - I've just changed it so that it fits your logic
2

Here is the correction

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)

The error is because you are trying to "talk" to VBA like a person do, but the or does not take the parameter of another or. You need to tell in every parameter of each or to tell the complete logical test

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

2 Comments

Done! Thanks Cody Gray and ElbertV
IMHO the syntax is right but the logic is wrong. Sorry!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.