Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA If <any of these> = <value>?

I'm fairly new to VBA, and I can't find an easy way to test if any of the specified variables equal a specified value. The below seems to work, but is there an easier way to do it?

If variable1 = 1 Or variable2 = 1 Or variable3 = 1 Or variable4 = 1 Or variable5 = 1 Then End If

I've also tried the following, with no luck.

If (variable1 Or variable2 Or variable3 Or variable4 Or variable5) = 1 Then End If
like image 424
John Smith Avatar asked Jul 17 '14 12:07

John Smith


People also ask

How do you use if then in a VBA statement?

IF THEN is a simple form of VBA statement. The format to write a code is: If <condition is true> Then <Statement>. You should use matching End If statement after entering the above syntax, When the condition meets or criteria evaluates to true, then all the lines between If Then and End If are processed.

What is not in VBA if not?

VBA IF Not. In any programming language, we have logical operators AND OR and NOT. Every operator has a specific function to do. AND combines two or more statements and return values true if every one of the statements is true where is in OR operator if any one of the statements is true the value is true. The NOT operator is a different thing.

What are the parameters of VBA if statements?

Parameters of VBA IF Statements 1 A condition or parameter to test. 2 An operation or task to perform if the condition is TRUE. 3 An operation or task to perform if the condition is FALSE More ...

What is the result of the if function in Excel?

If the specified value exists in the range the Excel IF function will return a "Yes" value. METHOD 1. If a range contains a specific value by row using VBA


1 Answers

You can use select case :)

Sub Sample()
    Dim variable1, variable2, variable3, variable4, variable5

    variable1 = 1: variable2 = 1: variable3 = 1: variable4 = 1: variable5 = 1

    Select Case 1
        Case variable1, variable2, variable3, variable4, variable5
            MsgBox "One of them is equal to 1"
        Case Else
            MsgBox "none of then is equal to 1"
    End Select
End Sub
like image 77
Siddharth Rout Avatar answered Oct 17 '22 20:10

Siddharth Rout