Excel vba if then with or

IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.

IF OR Function in VBA

Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.

Table of contents
  • IF OR Function in VBA
    • How to Use IF with OR Function in VBA?
    • IF OR VBA Function with Loops (Advanced)
    • Recommended Articles

VBA IF OR

How to Use IF with OR Function in VBA?

We will show you a simple example of using the IF OR function in VBA.

You can download this VBA IF OR Excel Template here – VBA IF OR Excel Template

A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.

Now, look at the syntax of the IF OR function in VBA.

[Test] OR [Test] OR [Test]

It is the same as we saw in the worksheet example. For a better understanding, look at the below example.

VBA IF OR Example 1

We have the previous month’s price, the last 6-month average price, and the current monthly price here.

To decide whether to buy the product, we need to do some tests here, and those tests are.

If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”

Step 1: Open the IF condition inside the Sub procedure.

Code:

Sub IF_OR_Example1()

 If

End Sub

VBA IF OR Example 1-1

Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value <= Range(“B2”).Value

Code:

Sub IF_OR_Example1()

 If Range(“D2”).Value <= Range(“B2”).Value

End Sub

VBA IF OR Example 1-2

Step 3: The first logical condition completes. Now, open OR statement.

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value OR

End Sub

VBA IF OR Example 1-3

Step 4: Now, apply the second logical condition as Range(“D2”).Value <= Range(“C2”).Value

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value OR Range("D2").Value <= Range("C2").Value

End Sub

VBA IF OR Example 1-4

Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then

End Sub

VBA IF OR Example 1-5

Step 6: In the next line, write what the result should be if the logical testA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then  

    Range("E2").Value = "Buy"

End Sub

VBA IF OR Example 1-6

Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.

Code:

Sub IF_OR_Example1()

If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then 

   Range("E2").Value = "Buy"
Else
   Range("E2").Value = "Do Not Buy"

End Sub

VBA IF OR Example 1-7

Step 8: Close the IF statement with “End If.”

Code:

Sub IF_OR_Example1()

If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then

   Range("E2").Value = "Buy"
Else
   Range("E2").Value = "Do Not Buy"
End If

End Sub

VBA IF OR Example 1-8

We complete the coding part.

Let us run this code using F5 or manually through the run option and see the result in cell E2.

Example 1-9

We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.

IF OR VBA Function with Loops (Advanced)

Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loopsA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more.

We have added a few more lines for the above data set.

Example 2

We need to use the For Next Loop here.

Just keep the current code as it is.

Declare the variable as an Integer.

Example 2-1

Now, open For Next Loop from 2 to 9.

Example 2-2

Now, wherever we have cell referenceCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more, change the current number, and concatenate the variable “k” with them.

For example, Range (“D2”).Value should be Range (“D” & k).Value

Example 2-3

Now, run the code. First, we should get the status in all the cells.

Example 2-4

You can copy the code below.

Code:

Sub IF_OR_Example1()

Dim k As Integer

For k = 2 To 9

If Range("D" & k).Value <= Range("B" & k).Value Or Range("D" & k).Value <= Range("C" & k).Value Then

Range("E" & k).Value = "Buy"
Else

Range("E" & k).Value = "Do Not Buy"

End If

Next k

End Sub

Recommended Articles

This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –

  • VBA INT
  • VBA LEN
  • VBA Integer
  • VBA MID Function

In this Article

  • VBA If Statement
    • If Then
  • ElseIF – Multiple Conditions
  • Else
  • If-Else
  • Nested IFs
  • IF – Or, And, Xor, Not
    • If Or
    • If And
    • If Xor
    • If Not
  • If Comparisons
    • If – Boolean Function
    • Comparing Text
    • VBA If Like
  • If Loops
  • If Else Examples
    • Check if Cell is Empty
    • Check if Cell Contains Specific Text
    • Check if cell contains text
    • If Goto
    • Delete Row if Cell is Blank
    • If MessageBox Yes / No
  • VBA If, ElseIf, Else in Access VBA

VBA If Statement

vba else if statement

If Then

VBA If Statements allow you to test if expressions are TRUE or FALSE, running different code based on the results.

Let’s look at a simple example:

If Range("a2").Value > 0 Then Range("b2").Value = "Positive"

This tests if the value in Range A2 is greater than 0. If so, setting Range B2 equal to “Positive”

vba if then

Note: When testing conditions we will use the =, >, <, <>, <=, >= comparison operators. We will discuss them in more detail later in the article.

Here is the syntax for a simple one-line If statement:

If [test_expression] then [action]

To make it easier to read, you can use a Line Continuation character (underscore) to expand the If Statements to two lines (as we did in the above picture):

If [test_expression] then _
    [action]
If Range("a2").Value > 0 Then _
   Range("b2").Value = "Positive"

End If

The above “single-line” if statement works well when you are testing one condition. But as your IF Statements become more complicated with multiple conditions, you will need to add an “End If” to the end of the if statement:

If Range("a2").Value > 0 Then
  Range("b2").Value = "Positive"
End If

vba end if

Here the syntax is:

If [test_expression] then
  [action]
End If

The End If signifies the end of the if statement.

Now let’s add in an ElseIF:

ElseIF – Multiple Conditions

The ElseIf is added to an existing If statement. ElseIf tests if a condition is met ONLY if the previous conditions have not been met.

In the previous example we tested if a cell value is positive. Now we will also test if the cell value is negative with an ElseIf:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
End If

vba elseif

You can use multiple ElseIfs to test for multiple conditions:

Sub If_Multiple_Conditions()

    If Range("a2").Value = "Cat" Then
        Range("b2").Value = "Meow"
    ElseIf Range("a2").Value = "Dog" Then
        Range("b2").Value = "Woof"
    ElseIf Range("a2").Value = "Duck" Then
        Range("b2").Value = "Quack"
    End If

End Sub

Now we will add an Else:

Else

The Else will run if no other previous conditions have been met.

We will finish our example by using an Else to indicate that if the cell value is not positive or negative, then it must be zero:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
Else
    Range("b2").Value = "Zero"
End If

vba else

If-Else

The most common type of If statement is a simple If-Else:

Sub If_Else()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        Range("b2").Value = "Not Positive"
    End If
End Sub

vba if else

Nested IFs

You can also “nest” if statements inside of each other.

Sub Nested_Ifs()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        If Range("a2").Value < 0 Then
            Range("b2").Value = "Negative"
        Else
            Range("b2").Value = "Zero"
        End If
    End If
End Sub

nested ifs

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

IF – Or, And, Xor, Not

Next we will discuss the logical operators: Or, And, Xor, Not.

If Or

The Or operator tests if at least one condition is met.

The following code will test if the value in Range A2 is less than 5,000 or greater than 10,000:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Then
    Range("b2").Value = "Out of Range"
End If

if or

You can include multiple Ors in one line:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Or Range("a2").Value = 9999 Then
    Range("b2").Value = "Out of Range"
End If

If you are going to use multiple Ors, it’s recommended to use a line continuation character to make your code easier to read:

If Range("a2").Value < 5000 Or _
   Range("a2").Value > 10000 Or _
   Range("a2").Value = 9999 Then

       Range("b2").Value = "Out of Range"
End If

vba multiple ors

If And

The And operator allows you to test if ALL conditions are met.

If Range("a2").Value >= 5000 And Range("a2").Value <= 10000 Then
    Range("b2").Value = "In Range"
End If

vba if and

VBA Programming | Code Generator does work for you!

If Xor

The Xor operator allows you to test if exactly one condition is met. If zero conditions are met Xor will return FALSE, If two or more conditions are met, Xor will also return false.

I’ve rarely seen Xor used in VBA programming.

If Not

The Not operator is used to convert FALSE to TRUE or TRUE To FALSE:

Sub IF_Not()
    MsgBox Not (True)
End Sub

vba if not

Notice that the Not operator requires parenthesis surrounding the expression to switch.

The Not operator can also be applied to If statements:

If Not (Range("a2").Value >= 5000 And Range("a2").Value <= 10000) Then
    Range("b2").Value = "Out of Range"
End If

if not

If Comparisons

When making comparisons, you will usually use one of the comparison operators:

Comparison Operator Explanation
= Equal to
<> Not Equal to
> Greater than
>= Greater than or Equal to
< Less than
<= Less than or Equal to

However, you can also use any expression or function that results in TRUE or FALSE

If – Boolean Function

When build expressions for If Statements, you can also use any function that generates TRUE or False.  VBA has a few of these functions:

Function Description
IsDate Returns TRUE if expression is a valid date
IsEmpty Check for blank cells or undefined variables
IsError Check for error values
IsNull Check for NULL Value
IsNumeric Check for numeric value

They can be called like this:

If IsEmpty(Range("A1").Value) Then MsgBox "Cell Empty"

Excel also has many additional functions that can be called using WorksheetFunction. Here’s an example of the Excel IsText Function:

If Application.WorksheetFunction.IsText(Range("a2").Value) Then _ 
   MsgBox "Cell is Text"

You can also create your own User Defined Functions (UDFs). Below we will create a simple Boolean function that returns TRUE. Then we will call that function in our If statement:

Sub If_Function()

If TrueFunction Then
    MsgBox "True"
End If

End Sub

Function TrueFunction() As Boolean
    TrueFunction = True
End Function

vba if boolean function

Comparing Text

You can also compare text similar to comparing numbers:

Msgbox "a" = "b"
Msgbox "a" = "a"

When comparing text, you must be mindful of the “Case” (upper or lower).  By default, VBA considers letters with different cases as non-matching.  In other words, “A” <> “a”.

If you’d like VBA to ignore case, you must add the Option Compare Text declaration to the top of your module:

Option Compare Text

After making that declaration “A” = “a”:

Option Compare Text

Sub If_Text()
   MsgBox "a" = "A"
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA If Like

The VBA Like Operator allows you to make inexact comparisons of text. Click the “Like Operator” link to learn more, but we will show a basic example below:

Dim strName as String
strName = "Mr. Charles"

If strName Like "Mr*" Then
    MsgBox "True"
Else
    MsgBox "False"
End If

Here we’re using an asterisk “*” wildcard. The * stands for any number of any characters.  So the above If statement will return TRUE.  The Like operator is an extremely powerful, but often under-used tool for dealing with text.

If Loops

VBA Loops allow you to repeat actions. Combining IF-ELSEs with Loops is a great way to quickly process many calculations.

Continuing with our Positive / Negative example, we will add a For Each Loop to loop through a range of cells:

Sub If_Loop()
Dim Cell as Range

  For Each Cell In Range("A2:A6")
    If Cell.Value > 0 Then
      Cell.Offset(0, 1).Value = "Positive"
    ElseIf Cell.Value < 0 Then
      Cell.Offset(0, 1).Value = "Negative"
    Else
      Cell.Offset(0, 1).Value = "Zero"
     End If
  Next Cell

End Sub

vba else if statement

If Else Examples

Now we will go over some more specific examples.

Check if Cell is Empty

This code will check if a cell is empty. If it’s empty it will ignore the cell. If it’s not empty it will output the cell value to the cell to the right:

Sub If_Cell_Empty()

If Range("a2").Value <> "" Then
    Range("b2").Value = Range("a2").Value
End If

End Sub

vba if cell empty do nothing

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Check if Cell Contains Specific Text

The Instr Function tests if a string of text is found in another string. Use it with an If statement to check if a cell contains specific text:

If Instr(Range("A2").value,"text") > 0 Then
  Msgbox "Text Found"
End If

Check if cell contains text

This code will test if a cell is text:

Sub If_Cell_Is_Text()

If Application.WorksheetFunction.IsText(Range("a2").Value) Then
    MsgBox "Cell is Text"
End If

End Sub

If Goto

You can use the result of an If statement to “Go to” another section of code.

Sub IfGoTo ()

    If IsError(Cell.value) Then
        Goto Skip
    End If

    'Some Code

Skip:
End Sub

Delete Row if Cell is Blank

Using Ifs and loops you can test if a cell is blank and if so delete the entire row.

Sub DeleteRowIfCellBlank()

Dim Cell As Range

For Each Cell In Range("A2:A10")
    If Cell.Value = "" Then Cell.EntireRow.Delete
Next Cell

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

If MessageBox Yes / No

With VBA Message Boxes you’re able to ask the user to select from several options. The Yes/No Message Box asks the user to select Yes or No.  You can add a Yes / No Message Box to a procedure to ask the user if they would like to continue running the procedure or not. You handle the user’s input using an If statement.

Here is the Yes/No Message Box in practice:

vba yes no msgbox

Sub MsgBoxVariable()

Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

VBA If, ElseIf, Else in Access VBA

The If, ElseIf and Else functions work exactly the same in Access VBA as in Excel VBA.

You can use an If statement to check if there are records in a Recordset.

vba yes no msgbox

Home / VBA / VBA IF OR (Test Multiple Conditions)

You can use the OR operator with the VBA IF statement to test multiple conditions. When you use it, it allows you to test two or more conditions simultaneously and returns true if any of those conditions are true. But if all the conditions are false only then it returns false in the result.

Use OR with IF

  1. First, start the IF statement with the “IF” keyword.
  2. After that, specify the first condition that you want to test.
  3. Next, use the OR keyword to specify the second condition.
  4. In the end, specify the second condition that you want to test.

To have a better understanding let’s see an example.

Sub myMacro()

'two conditions to test using OR
If 1 = 1 Or 2 < 1 Then
    MsgBox "One of the conditions is true."
Else
    MsgBox "None of the conditions are true."
End If

End Sub

If you look at the above example, we have specified two conditions one if (1 = 1) and the second is (2 < 1), and here only the first condition is true, and even though it has executed the line of code that we have specified if the result is true.

Now let’s see if both conditions are false, let me use a different code here.

Sub myMacro()

'two conditions to test using OR
If 1 = 2 Or 2 < 1 Then
    MsgBox "One of the conditions is true."
Else
    MsgBox "None of the conditions are true."
End If

End Sub

In the above code, both conditions are false, and when you run this code, it executes the line of code that we have specified if the result is false.

In the same way, you can also test more than two conditions at the same time. Let’s continue the above example and add the third condition to it.

Sub myMacro()

'three conditions to test using OR

If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then
    MsgBox "one of the conditions is true."
Else
    MsgBox "none of the conditions are true."
End If

End Sub

Now we have three conditions to test, and we have used the OR after the second condition to specify the third condition. As you learned above that when you use OR, any of the conditions need to be true to get true in the result. When you run this code, it executes the line of code that we have specified for the true.

And if all the conditions are false, just like you have in the following code, it returns false.

Sub myMacro()

'three conditions to test using OR
If 1 < 1 And 2 < 1 And 1 + 1 = 0 Then

    MsgBox "one of the conditions is true."

Else

    MsgBox "none of the conditions are true."

End If

End Sub

Содержание

  1. If Then Else Statement in Excel VBA (explained with examples)
  2. Syntax – IF Then Else
  3. Examples of Using IF Then Statement in VBA
  4. Nested IF Then (Multiple IF Then statements)
  5. Multiple IF Then Statements
  6. IF Then Else Statement
  7. IF Then ElseIf Else Statement
  8. Using AND and OR in IF Then Else
  9. Using Not Equal to in If Then
  10. Using If Then Else with Loops in VBA
  11. Example 1 – Save and Close All Workbooks Except The Active Workbook
  12. Example 2 – Highlight Cells with Negative Values
  13. Example 3 – Hide All the Worksheet Except the Current Worksheet
  14. Example 4 – Extract the Numeric Part from an Alphanumeric String
  15. Where to Put the VBA Code?
  16. VBA If – And, Or, Not
  17. IF…AND
  18. IF NOT…
  19. VBA Code Examples Add-in
  20. VBA IF OR
  21. IF OR Function in VBA
  22. How to Use IF with OR Function in VBA?
  23. IF OR VBA Function with Loops (Advanced)
  24. Recommended Articles

If Then Else Statement in Excel VBA (explained with examples)

In Excel VBA, IF Then Else statement allows you to check for a condition, and perform an action accordingly.

This is extremely valuable in many situations as we will see in the examples later in this tutorial.

To give you a simple example, suppose you have a list of grades in Excel and you want to highlight all those students who have scored an A. Now, if I ask you to do this manually, you will check each student’s grade and if it’s an A, you’ll highlight it, and if it isn’t, then you’ll leave it as is.

The same logic can be built in VBA using the If Then Else statement as well (and of course do a lot more than just highlighting grades).

In this tutorial, I’ll show you different ways the ‘If Then Else’ construct can be used in Excel VBA, and some practical examples in action.

But before I get into the specifics, let me give you the syntax of the ‘IF Then Else’ statement.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

This Tutorial Covers:

Syntax – IF Then Else

Below is the generic syntax of If Then Else construct in VBA

Note that the Else part of this statement is optional.

Now if you’re wondering what’s the difference between the two syntaxes, let me clarify.

The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement.

However, in the second syntax, the true_code part is in the second line. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines.

When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends.

Hence you need to use the End IF statement.

In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”

Examples of Using IF Then Statement in VBA

To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial).

Suppose you have a student’s score in cell A1 and you want to check whether the student passed the exam or not (passing marks threshold being 35).

Then you can use the following code:

The above code has a single line of IF statement that checks the value in cell A1.

If it’s more than 35, it shows the message – “Pass”.

If it’s less than 35, nothing happens.

But what if you want to show a message in both the cases, whether a student passed or failed the exam.

The below code would do this:

The above code uses the IF as well as the ELSE statement to execute two different conditions. When the score is more than (or equal to) 35, the IF condition is true, and the code right below it gets executed (everything before the Else statement).

But when the IF condition is FALSE, the code jumps to the Else part and executes the code block in it.

Note that when we use a single line of IF Then statement, we don’t need to use End IF. But when we split it into more than one line, we need to use the End If statement.

Nested IF Then (Multiple IF Then statements)

So far we have used a single IF Then statement.

In case you have multiple conditions to check, you can use:

  • Multiple IF conditions
  • If Then Else statement
  • IF Then ElseIf Else construct

Let me show you how these differ and how to use this in Excel VBA.

Multiple IF Then Statements

Let’s take the same example of using a student’s score.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’.

We can use the below code to get this done:

You can use multiple IF Then statement as shown above. While this works, it’s not an example of good coding (as you will see the alternatives below).

In case you decide to use this, remember that these statements should either be independent or mutually exclusive. The important thing to know here is that in the above construct, all the IF statements are evaluated and the ones where the condition is true, the code is executed.

So even if the first IF statement is correct, the second would still be evaluated.

IF Then Else Statement

Suppose this time, instead of just displaying the message Pass/Fail, we have one more condition.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

We can use the below code to get this done:

In the above code, we have used multiple IF statements (nested IF Then) with the help of Else.

So there is an ‘IF Then Else’ construct within an ‘IF Then Else’ construct. This type of nesting allows you to check for multiple conditions and run the relevant block of code.

IF Then ElseIf Else Statement

The above code (that we saw in the previous section) can be further optimized by using the ElseIf statement.

Here is what we’re trying to do – If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

The above code uses ElseIf, which allows us to keep all the conditions within one single IF Then statement.

Using AND and OR in IF Then Else

So far in this tutorial, we have only checked for a single condition at a time.

However, when you have multiple dependent conditions, you can use the AND or OR statement with the IF conditions.

Below is the syntax of using AND/OR condition with the IF Then statement.

In the above code, only when both Condition1 and Condition2 are met, the true_code is executed. Even if one of the conditions is false, it will execute the false_code.

With OR, even if one of the conditions are true, it will execute the true_code. Only when all the conditions are false, it executes the false_code.

Now let’s see how AND and OR statement work with the IF Then Else construct.

Suppose you have the scores for two subjects instead of one, and you want to check for the following conditions:

  • Fail – When the score is less than 35 in any of the subjects.
  • Pass – When the score is more than or equal to 35, but less than 80 in both the subjects.
  • Pass, with Distinction – When the score is more than 35 in both the subjects and is more than or equal to 80 in one or both the subjects.

Here is the code that will do this:

The above code uses both OR and AND statements.

You can also write this same code with a slight change (using OR instead of AND).

Both the above VBA codes will give you the same result. Personally, I prefer the first one as it has a logical flow of checking the scores (but that’s just me).

Using Not Equal to in If Then

In all the examples above, we have used the conditions that check whether a value equal to a specified value or not.

You can also use similar codes when checking when the value is not equal to a specified value in the VBA code. Not equal to represented by <> the Excel VBA.

To see a practical example of using <>, have a look at Example 1 below.

Using If Then Else with Loops in VBA

So far, we have been going through some examples that are good to understand how the ‘IF-THEN’ statements work in VBA, however, are not useful in the practical world.

If I need to grade students, I can easily do that using Excel functions.

So let’s have a look at some useful and practical examples that can help you automate some stuff and be more efficient.

Example 1 – Save and Close All Workbooks Except The Active Workbook

If you have a lot of workbooks open and you quickly want to close all, except the active workbook, you can use the below code,

The above code would save and close all the workbooks (except the active one).

It uses the For Next loop to go through the collection of all the open workbooks and checks the name using the IF condition.

If the name is not the same as that of the Active workbook, it saves and closes it.

In case there is a VBA code in any of the workbooks and you haven’t saved it as .xls or .xlsm, you will see a warning (as the vba codes are lost when you save it in .xlsx format).

Example 2 – Highlight Cells with Negative Values

Suppose that you have a column full of numbers and you want to quickly highlight all the cells with negative values in red, you can do that using the below code.

The above code uses the For Each loop and checks each cell in the selection that you have made. If the cell has a value that is negative, it’s highlighted in red with white font color.

Example 3 – Hide All the Worksheet Except the Current Worksheet

In case you want to quickly hide all the worksheets except the active one, you can use the below code:

The above code uses the For Each loop to go through a collection of worksheets. It checks the name of each worksheet and hides it if it’s not the active worksheet.

If you have alphanumeric strings in cells and you want to extract the numeric part from it, you can do that using the below code:

This code will create a custom function in Excel that can use within the worksheet (just like a regular function).

Where to Put the VBA Code?

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VB editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.
  2. Click on Visual Basic option. This will open the VB editor in the backend.
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.
  5. Copy and paste the code in the module window.

You May Also Like the Following Excel Tutorials:

Источник

VBA If – And, Or, Not

In this Article

This article will demonstrate how to use the VBA If statement with And, Or and Not.

When we us an IF statement in Excel VBA, the statement will execute a line of code if the condition you are testing is true.

  • We can use AND statement and OR statements in conjunction with IF statements to test for more than one condition and direct the code accordingly.
  • We can also use a NOT statement with an IF statement to check if the condition is NOT true – it basically is the inverse of the IF statement when used alone.

IF…AND

We can use the IF…AND combination of logical operators when we wish to test for more than one condition where all the conditions need to be true for the next line of code to execute.

For example, consider the following sheet:

To check if the Profit is over $5,000, we can run the following macro:

This macro will check that the cell C5 is greater or equal to $10,000 AND check that the cell B6 is less than $5,000. If these conditions are BOTH true, it will show the message box.

If we amend the macro to check if C5 is just greater than $10,000, then the profit would not be achieved!

We can use the IF…OR combination of logical operators when we wish to test for more than one condition where only one of the conditions needs to be true for the next line of code to execute.

The format for this is almost identical to the IF…AND example above.

However, with this macro, because we are using an IF …OR statement, only one of the conditions needs to be true.

IF NOT…

IF..NOT changes the IF statement around – it will check to see if the condition is NOT true rather than checking to see if the condition is true.

In this example above, the IF statement is checking to see if the value in C5 is NOT smaller than 10000.

Therefore this line of code:

and this this line of code:

are testing for the same thing!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA IF OR

IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.

IF OR Function in VBA

Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA IF OR (wallstreetmojo.com)

How to Use IF with OR Function in VBA?

We will show you a simple example of using the IF OR function in VBA.

A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.

Now, look at the syntax of the IF OR function in VBA.

It is the same as we saw in the worksheet example. For a better understanding, look at the below example.

We have the previous month’s price, the last 6-month average price, and the current monthly price here.

To decide whether to buy the product, we need to do some tests here, and those tests are.

If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”

Step 1: Open the IF condition inside the Sub procedure.

Code:

Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value

Step 3: The first logical condition completes. Now, open OR statement.

Code:

Step 4: Now, apply the second logical condition as Range(“D2”).Value

Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”

Code:

Step 6: In the next line, write what the result should be if the logical test Logical Test A logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test. read more is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.

Code:

Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.

Code:

Step 8: Close the IF statement with “End If.”

Code:

We complete the coding part.

Let us run this code using F5 or manually through the run option and see the result in cell E2.

We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.

IF OR VBA Function with Loops (Advanced)

Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loops Use VBA Loops A VBA loop in excel is an instruction to run a code or repeat an action multiple times. read more .

We have added a few more lines for the above data set.

We need to use the For Next Loop here.

Just keep the current code as it is.

Declare the variable as an Integer.

Now, open For Next Loop from 2 to 9.

For example, Range (“D2”).Value should be Range (“D” & k).Value

Now, run the code. First, we should get the status in all the cells.

You can copy the code below.

Code:

Recommended Articles

This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –

Источник

На чтение 19 мин. Просмотров 24.3k.

VBA If Statement

Пьер Корнель

Угадай, если сможешь, и выбери, если посмеешь

Содержание

  1. Краткое руководство по VBA If Statement
  2. Что такое IF  и зачем оно тебе?
  3. Тестовые данные
  4. Формат операторов VBA If Then
  5. Простой пример If Then
  6. Условия IF
  7. Использование If ElseIf
  8. Использование If Else
  9. Используя If And/If Or
  10. Функция IIF
  11. Использование Select Case
  12. Попробуйте это упражнение

Краткое руководство по VBA If Statement

Описание Формат Пример
If Then If [условие верно] 
Then [действие]
End If
If score = 100 
Then Debug.Print
«Отлично» 
End If
If Else If [условие верно]
Then [действие]
Else [действие]
End If
If score = 100 
Then Debug.Print 
«Отлично» 
Else Debug.Print 
«Попробуй снова» 
End If
If ElseIf If [1 условие верно] 
Then [действие]
ElseIf [2 условие
верно] 
Then [действие]
End If
If score = 100 
Then Debug.Print 
«Отлично» 
ElseIf score > 50 
Then Debug.Print 
«Пройдено» 
ElseIf score <= 50 
Then Debug.Print 
«Попробуй снова» 
End If
Else и ElseIf
(Else должно
идти
после ElseIf’s)
If [1 условие верно] 
Then [действие]
ElseIf [2 условие
верно] 
Then [действие]
Else [действие]
End If
If score = 100 
Then Debug.Print 
«Отлично» 
ElseIf score > 50 
Then Debug.Print 
«Пройдено» 
ElseIf score > 30 
Then Debug.Print 
«Попробуй снова» 
Else Debug.Print 
«Ой» 
End If
If без Endif
(Только одна
строка)
If [условие верно] 
Then [действие]
If value <= 0 
Then value = 0

В следующем коде показан простой пример использования
оператора VBA If

If Sheet1.Range("A1").Value > 5 Then
    Debug.Print "Значение больше 5."
ElseIf Sheet1.Range("A1").Value < 5 Then
    Debug.Print "Значение меньше 5."
Else
    Debug.Print "Значение равно 5."
End If

Что такое IF  и зачем оно тебе?

Оператор VBA If используется, чтобы позволить вашему коду
делать выбор, когда он выполняется.

Вам часто захочется сделать выбор на основе данных, которые
читает ваш макрос.

Например, вы можете захотеть читать только тех учеников, у
которых оценки выше 70. Когда вы читаете каждого учащегося, вы можете
использовать инструкцию If для проверки отметок каждого учащегося.

Важным словом в последнем предложении является проверка. Оператор
If используется для проверки значения, а затем для выполнения задачи на основе
результатов этой проверки.

Тестовые данные

Мы собираемся использовать следующие тестовые данные для
примеров кода в этом посте.

VBA If Sample Data

Формат операторов VBA If Then

Формат оператора If Then следующий

За ключевым словом If следуют условие и ключевое слово Then

Каждый раз, когда вы используете оператор If Then, вы должны использовать соответствующий оператор End If.

Когда условие оценивается как истинное, обрабатываются все
строки между If Then и End If.

If [условие верно] Then
    [строки кода]
    [строки кода]
    [строки кода]
End If

Чтобы сделать ваш код более читабельным, рекомендуется
делать отступы между операторами If Then и End If.

Отступ между If и End If

Отступ означает просто переместить строку кода на одну вкладку вправо. Правило большого пальца состоит в том, чтобы сделать отступ между начальным и конечным операторами, такими как:

Sub … End Sub
If Then … End If
If Then… ElseIf … Else … Endif
For … Next
Do While … Loop
Select Case … End Case

Для отступа в коде вы можете выделить строки для отступа и нажать клавишу Tab. Нажатие клавиш Shift + Tab сделает отступ кода, т.е. переместит его на одну вкладку влево.

Вы также можете использовать значки на панели инструментов Visual Basic для отступа кода.

VBA If

Если вы посмотрите на примеры кода на этом сайте, вы увидите, что код имеет отступ.

Простой пример If Then

Следующий код выводит имена всех студентов с баллами более 50.

Sub ChitatOcenki()
    
    Dim i As Long
    ' Пройдите столбцы отметок
    For i = 2 To 11
        ' Проверьте, больше ли баллов,чем 50
        If Sheet1.Range("C" & i).Value > 50 Then
            ' Напечатайте имя студента в «Immediate Window» (Ctrl + G)
            Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value
        End If
    
    Next
    
End Sub

Результаты:

  • Василий Кочин
  • Максим Бородин
  • Дмитрий Маренин
  • Олеся Клюева
  • Евгений Яшин

Поэкспериментируйте с этим примером и проверьте значение или знак > и посмотрите, как изменились результаты.

Условия IF

Часть кода между ключевыми словами If и Then называется условием. Условие — это утверждение, которое оценивается как истинное или ложное. Они в основном используются с операторами Loops и If. При создании условия вы используете такие знаки, как «>, <, <>,> =, <=, =».

Ниже приведены примеры условий:

Условие Это верно, когда
x < 5 x меньше,чем 5
x <= 5 x меньше, либо равен 5
x > 5 x больше, чем 5
x >= 5 x больше, либо равен 5
x = 5 x равен 5
x <> 5 x не равен 5
x > 5 And x < 10 x больше, чем 5 И x меньше, чем 10
x = 2 Or x >10 x равен 2 ИЛИ x больше,чем 10
Range(«A1») = «Иван» Ячейка A1 содержит текст «Иван»
Range(«A1») <> «Иван» Ячейка A1 не содержит текст «Иван»

Вы могли заметить x = 5, как условие. Не стоит путать с х = 5, при использовании в качестве назначения.

Когда в условии используется «=», это означает, что «левая сторона равна правой стороне».

В следующей таблице показано, как знак равенства используется
в условиях и присваиваниях.

Использование «=» Тип Значение
Loop Until x = 5 Условие Равен ли x пяти
Do While x = 5 Условие Равен ли x пяти
If x = 5 Then Условие Равен ли x пяти
For x = 1 To 5 Присваивание Установите значение х = 1, потом = 2 и т.д.
x = 5 Присваивание Установите х до 5
b = 6 = 5 Присваивание и
условие
Присвойте b
результату условия
6 = 5
x = MyFunc(5,6) Присваивание Присвойте х
значение,
возвращаемое
функцией

Последняя запись в приведенной выше таблице показывает
оператор с двумя равными. Первый знак равенства — это присвоение, а любые
последующие знаки равенства — это условия.

Поначалу это может показаться странным, но подумайте об этом
так. Любое утверждение, начинающееся с переменной и равно, имеет следующий
формат

[переменная] [=] [оценить эту часть]

Поэтому все, что находится справа от знака равенства, оценивается и результат помещается в переменную. Посмотрите на последние три строки таблицы, как:

[x] [=] [5]

[b] [=] [6 = 5]

[x] [=] [MyFunc (5,6)]

Использование If ElseIf

Инструкция ElseIf позволяет вам выбирать из нескольких вариантов. В следующем примере мы печатаем баллы, которые находятся в диапазоне.

Sub IspElseIf()
    
    If Marks >= 85 Then
        Debug.Print "Высший балл"
    ElseIf Marks >= 75 Then
        Debug.Print "Отлично"
    End If
    
End Sub

Важно понимать, что порядок важен. Условие If проверяется
первым.

Если это правда, то печатается «Высший балл», и оператор If заканчивается.

Если оно ложно, то код переходит к следующему ElseIf и
проверяет его состояние.

Давайте поменяемся местами If и ElseIf из последнего
примера. Код теперь выглядит так

Sub IspElseIfNeverno()
    
    ' Этот код неверен, так как ElseIf никогда не будет верным
    If Marks >= 75 Then
        Debug.Print "Отлично"
    ElseIf Marks >= 85 Then
        ' код никогда не достигнет здесь
        Debug.Print "Высший балл"
    End If
    
End Sub

В этом случае мы сначала проверяем значение более 75. Мы никогда не будем печатать «Высший балл», потому что, если значение больше 85, это вызовет первый оператор if.

Чтобы избежать подобных проблем, мы должны использовать два
условия. Они помогают точно указать, что вы ищете, чтобы избежать путаницы.
Пример ниже показывает, как их использовать. Мы рассмотрим более многочисленные
условия в разделе ниже.

If marks >= 75 And marks < 85 Then
    Debug.Print "Отлично"
ElseIf marks >= 85 And marks <= 100 Then
    Debug.Print "Высший балл"
End If

Давайте расширим оригинальный код. Вы можете использовать столько операторов ElseIf, сколько захотите. Мы добавим еще несколько, чтобы учесть все наши классификации баллов.

Использование If Else

Утверждение Else используется, как ловушка для всех. Это в основном означает «если бы не было условий» или «все остальное». В предыдущем примере кода мы не включили оператор печати для метки сбоя. Мы можем добавить это, используя Else.

Sub IspElse()
    
    If Marks >= 85 Then
        Debug.Print "Высший балл"
    ElseIf Marks >= 75 Then
        Debug.Print "Отлично"
    ElseIf Marks >= 55 Then
        Debug.Print "Хорошо"
    ElseIf Marks >= 40 Then
        Debug.Print "Удовлетворительно"
    Else
        ' Для всех других оценок
        Debug.Print "Незачет"
    End If
    
End Sub

Так что, если это не один из других типов, то это провал.

Давайте напишем некоторый код с помощью наших примеров
данных и распечатаем студента и его классификацию.

Sub DobClass()
    
    ' получить последнюю строку
    Dim startRow As Long, lastRow As Long
    startRow = 2
    lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, Marks As Long
    Dim sClass As String

    ' Пройдите столбцы отметок
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Проверьте отметки и классифицируйте соответственно
        If Marks >= 85 Then
            sClass = "Высший балл"
        ElseIf Marks >= 75 Then
            sClass = "Отлично"
        ElseIf Marks >= 55 Then
            sClass = "Хорошо"
        ElseIf Marks >= 40 Then
            sClass = "Удовлетворительно"
        Else
            ' Для всех других оценок
            sClass = "Незачет"
        End If
    
        ' Запишите класс в столбец E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Результаты выглядят так: в столбце E — классификация баллов

VBA If ElseIf Class

Используя If And/If Or

В выражении If может быть несколько условий. Ключевые слова VBA And и Or позволяют использовать несколько условий.

Эти слова работают так же, как вы используете их на
английском языке.

Давайте снова посмотрим на наши примеры данных. Теперь мы
хотим напечатать всех студентов, которые набрали от 50 до 80 баллов.

Мы используем Аnd, чтобы добавить дополнительное условие. Код гласит: если оценка больше или равна 50 и меньше 75, напечатайте имя студента.

Sub ProverkaStrokiOcenok()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i).Value
        
        ' Проверьте, если отметки больше 50 и меньше 75
        If marks >= 50 And marks < 80 Then
             ' Напечатайте имя и фамилию в Immediate window (Ctrl+G)
             Debug.Print Sheet1.Range("A" & i).Value & Sheet1.Range("B" & i).Value
        End If
    
    Next

End Sub

Вывести имя и фамилию в результаты:

  • Дмитрий Маренин
  • Олеся Клюева
  • Евгений Яшин

В нашем следующем примере мы хотим знать, кто из студентов сдавал историю или геометрию. Таким образом, в данном случае мы говорим, изучал ли студент «История» ИЛИ изучал ли он «Геометрия» (Ctrl+G).

Sub ChitatObektOcenki()
    
    Dim i As Long, marks As Long
    
    ' Пройдите столбцы отметок
    For i = 2 To 11
        marks = Sheet1.Range("D" & i).Value
        ' Проверьте, если отметки больше 50 и меньше 80
        If marks = "История" Or marks = "Геометрия" Then
            ' Напечатайте имя и фамилию в Immediate window (Ctrl+G)
            Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value
        End If
    
    Next
    
End Sub

Результаты:

  • Василий Кочин
  • Александр Грохотов
  • Дмитрий Маренин
  • Николай Куликов
  • Олеся Клюева
  • Наталия Теплых
  • Дмитрий Андреев

Использование нескольких таких условий часто является
источником ошибок. Эмпирическое правило, которое нужно помнить, должно быть
максимально простым.

Использование IF AND

And работает следующим образом:

Условие 1 Условие 2 Результат
ИСТИНА ИСТИНА ИСТИНА
ИСТИНА ЛОЖЬ ЛОЖЬ
ЛОЖЬ ИСТИНА ЛОЖЬ
ЛОЖЬ ЛОЖЬ ЛОЖЬ

Что вы заметите, так это то, что And верно только тогда, когда все условия выполняются.

Использование IF OR

Ключевое слово OR работает следующим образом

Условие 1 Условие 2 Результат
ИСТИНА ИСТИНА ИСТИНА
ИСТИНА ЛОЖЬ ИСТИНА
ЛОЖЬ ИСТИНА ИСТИНА
ЛОЖЬ ЛОЖЬ ЛОЖЬ

Что вы заметите, так это то, что OR ложно, только когда все условия ложны.

Смешивание And и Or может затруднить чтение кода и привести к ошибкам. Использование скобок может сделать условия более понятными.

Sub OrSAnd()
    
 Dim subject As String, marks As Long
 subject = "История"
 marks = 5
    
 If (subject = "Геометрия" Or subject = "История") And marks >= 6 Then
     Debug.Print "ИСТИНА"
 Else
     Debug.Print "ЛОЖЬ"
 End If
    
End Sub

Использование IF NOT

Также есть оператор NOT. Он возвращает противоположный результат условия.

Условие Результат
ИСТИНА ЛОЖЬ
ЛОЖЬ ИСТИНА

Следующие две строки кода эквивалентны.

If marks < 40 Then 
If Not marks >= 40 Then

так же, как и

If True Then 
If Not False Then 

и

If False Then 
If Not True Then 

Помещение условия в круглые скобки облегчает чтение кода

If Not (marks >= 40) Then

Распространенное использование Not — при проверке, был ли установлен объект. Возьмите Worksheet для примера. Здесь мы объявляем рабочий лист.

Dim mySheet As Worksheet
' Некоторый код здесь

Мы хотим проверить действительность mySheet перед его использованием. Мы можем проверить, если это Nothing.

If mySheet Is Nothing Then

Нет способа проверить, является ли это чем-то, поскольку есть много разных способов, которым это может быть что-то. Поэтому мы используем NOT с Nothing.

If Not mySheet Is Nothing Then

Если вы находите это немного запутанным, вы можете использовать круглые скобки, как здесь

If Not (mySheet Is Nothing) Then

Функция IIF

VBA имеет функцию, аналогичную функции Excel If. В Excel вы часто используете функцию If следующим образом:

= ЕСЛИ (F2 =»»,»», F1 / F2)

Формат

= If (условие, действие, если ИСТИНА, действие, если ЛОЖЬ).

VBA имеет функцию IIf, которая работает так же. Давайте посмотрим на примере. В следующем коде мы используем IIf для проверки значения переменной val. Если значение больше 10, мы печатаем ИСТИНА, в противном случае мы печатаем ЛОЖЬ.

Sub ProveritVal()
 
    Dim result As Boolean
    Dim val As Long
    
    ' Печатает ИСТИНА
    val = 11
    result = IIf(val > 10, ИСТИНА, ЛОЖЬ)
    Debug.Print result
    
    ' печатает ЛОЖЬ
    val = 5
    result = IIf(val > 10, ИСТИНА, ЛОЖЬ)
    Debug.Print result
    
End Sub

В нашем следующем примере мы хотим распечатать «Удовлетворитеьно» или «Незачет» рядом с каждым студентом в зависимости от их баллов. В первом фрагменте кода мы будем использовать обычный оператор VBA If, чтобы сделать это.

Sub ProveritDiapazonOcenok()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i).Value
        
        ' Проверьте, прошел ли студент или нет
        If marks >= 40 Then
             ' Запишите имена для столбца F
             Sheet1.Range("E" & i) = "Удовлетворительно"
        Else
             Sheet1.Range("E" & i) = "Незачет"
        End If
    
    Next

End Sub

В следующем фрагменте кода мы будем использовать функцию IIf. Код здесь намного аккуратнее.

Sub ProveritDiapazonOcenok ()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i)
        
        ' Проверьте, прошел ли студент или нет
        Sheet1.Range("E" & i).Value = IIf(marks >= 40,"Удовлетворительно","Незачет")
    
    Next

End Sub

Функция IIf очень полезна для простых случаев, когда вы имеете дело с двумя возможными вариантами.

Использование Nested IIf

Вы также можете вкладывать IIf-операторы, как в Excel. Это означает использование результата одного IIf с другим. Давайте добавим еще один тип результата в наши предыдущие примеры. Теперь мы хотим напечатать «Отлично», «Удовлетворительно» или «Незачетт» для каждого студента.

Используя обычный VBA, мы сделали бы это так

Sub ProveritRezultatiTip2()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i).Value
        
        If marks >= 75 Then
             Sheet1.Range("E" & i).Value = "Отлично"
        ElseIf marks >= 40 Then
             ' Запишите имена для столбца F
             Sheet1.Range("E" & i).Value = "Удовлетворительно"
        Else
             Sheet1.Range("E" & i).Value = "Незачет"
        End If
    
    Next

End Sub

Используя вложенные IIfs, мы могли бы сделать это так

Sub IspNestedIIF()

Dim i As Long, marks As Long, result As String
For i = 2 To 11
    
marks = Sheet1.Range("C" & i).Value
result = IIf(marks >= 55,"Хорошо",IIf(marks >= 40,"Удовлетворительно","Незачет"))

Sheet1.Range("E" & i).Value = result

Next

End Sub

Использование вложенного IIf хорошо в простых случаях, подобных этому. Код прост для чтения и, следовательно, вряд ли вызовет ошибки.

Чего нужно остерегаться

Важно понимать, что функция IIf всегда оценивает как
Истинную, так и Ложную части выражения независимо от условия.

В следующем примере мы хотим разделить по баллам, когда он не равен нулю. Если он равен нулю, мы хотим вернуть ноль.

marks = 0
total = IIf(marks = 0, 0, 60 / marks)

Однако, когда отметки равны нулю, код выдаст ошибку «Делить на ноль». Это потому, что он оценивает как Истинные, так и Ложные утверждения. Здесь ложное утверждение, т.е. (60 / Marks), оценивается как ошибка, потому что отметки равны нулю.

Если мы используем нормальный оператор IF, он будет
запускать только соответствующую строку.

marks = 0
If marks = 0 Then
    'Выполняет эту строку только когда отметки равны нулю
    total = 0
Else
    'Выполняет только эту строку, когда отметки не равны нулю
    total = 60 / marks
End If

Это также означает, что если у вас есть функции для ИСТИНА и ЛОЖЬ, то обе будут выполнены. Таким образом, IIF будет запускать обе функции, даже если он использует только одно возвращаемое значение. Например:

' Обе функции будут выполняться каждый раз
total = IIf(marks = 0, Func1, Func2)

IF против IIf

Так что лучше?

В этом случае вы можете видеть, что IIf короче для написания и аккуратнее. Однако если условия усложняются, вам лучше использовать обычное выражение If. Недостатком IIf является то, что он недостаточно известен, поэтому другие пользователи могут не понимать его так же, как и код, написанный с помощью обычного оператора if.

Кроме того, как мы обсуждали в последнем разделе, IIF всегда оценивает части ИСТИНА и ЛОЖЬ, поэтому, если вы имеете дело с большим количеством данных, оператор IF будет быстрее.

Мое эмпирическое правило заключается в том, чтобы
использовать IIf, когда
он будет прост для чтения и не требует вызовов функций. Для более сложных
случаев используйте обычный оператор If.

Использование Select Case

Оператор Select Case
— это альтернативный способ написания статистики If с большим количеством ElseIf. Этот тип операторов
вы найдете в большинстве популярных языков программирования, где он называется
оператором Switch. Например,
Java, C #, C ++ и Javascript
имеют оператор switch.

Формат

Select Case [переменная]
    Case [условие 1]
    Case [условие 2]
    Case [условие n]
    Case Else
End Select

Давайте возьмем наш пример DobClass сверху и перепишем его с помощью оператора Select Case.

Sub DobavitClass()
    
    ' получить последнюю строку
    Dim startRow As Long, lastRow As Long
    startRow = 2
    lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, Marks As Long
    Dim sClass As String

    ' Пройдите столбцы отметок
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Проверьте отметки и классифицируйте соответственно
        If Marks >= 85 Then
            sClass = "Высший балл"
        ElseIf Marks >= 75 Then
            sClass = "Отлично"
        ElseIf Marks >= 55 Then
            sClass = "Хорошо"
        ElseIf Marks >= 40 Then
            sClass = "Удовлетворительно"
        Else
            ' Для всех других оценок
            sClass = "Незачет"
        End If
    
        ' Запишите класс в столбец E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Ниже приведен тот же код с использованием оператора Select Case. Главное, что вы заметите, это то, что мы используем “Case 85 to 100” rather than “marks >=85 And marks <=100”. , а не “marks >=85 And marks <=100”.

Sub DobavitClassSSelect()
    
    ' получить первую и последнюю строки
    Dim firstRow As Long, lastRow As Long
    firstRow = 2
    lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, marks As Long
    Dim sClass As String

    ' Пройдите столбцы отметок
    For i = firstRow To lastRow
        marks = Sheet1.Range("C" & i).Value
        ' Проверьте отметки и классифицируйте соответственно
        Select Case marks
        Case 85 To 100
            sClass = "Высший балл"
        Case 75 To 84
            sClass = "Отлично"
        Case 55 To 74
            sClass = "Хорошо"
        Case 40 To 54
            sClass = "Удовлетворительно"
        Case Else
            ' Для всех других оценок
            sClass = "Незачет"
        End Select
        ' Запишите класс в столбец E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Использование Case Is

Вы можете переписать оператор select в том же формате, что и оригинальный ElseIf. Вы можете использовать Is с Case.

Select Case marks
    Case Is >= 85
         sClass = "Высший балл"
    Case Is >= 75
        sClass = "Отлично"
    Case Is >= 55
        sClass = "Хорошо"
    Case Is >= 40
        sClass = "Удовлетворительно"
    Case Else
        ' Для всех других оценок
        sClass = "Незачет"
End Select

Вы можете использовать Is для проверки нескольких значений.
В следующем коде мы проверяем, равны ли оценки 5, 7 или 9.

Sub TestNeskZnach()
    
    Dim marks As Long
    marks = 7
    
    Select Case marks
        Case Is = 5, 7, 9
            Debug.Print True
        Case Else
            Debug.Print False
    End Select
    
End Sub

Попробуйте это упражнение

В этой статье много рассказывали о выражении If. Хороший способ помочь вам понять — это попытаться написать код, используя темы, которые мы рассмотрели. В следующем упражнении используются тестовые данные из этой статьи. Ответ на упражнение ниже.

Мы будем использовать ячейку G1, чтобы написать имя
субъекта.

В колонках от H до L запишите всех студентов, которые имеют оценки по этому предмету. Мы хотим классифицировать их результат как успешный или неудачный. Оценка ниже 40 — неудача, оценка 40 или выше — Зачет.

Колонка H: Имя

Колонка I: Фамилия

Колонка J: Баллы

Колонка H: Предмет

Столбец I: Тип результата — Зачет или Незачет

Если ячейка G1 содержит «Геометрия», то ваш результат должен выглядеть следующим образом:

VBA If Statement

Ответ на упражнение

Следующий код показывает, как выполнить вышеупомянутое упражнение.

Примечание: есть много способов выполнить задачу, поэтому не расстраивайтесь, если ваш код отличается.

Sub ZapisatRezultat()
     
    ' Получить тему
    Dim subject As String
    subject = Sheet1.Range("G1").Value
     
    If subject = "" Then
        Exit Sub
    End If
     
    ' Получить первый и последний ряд
    Dim firstRow As Long, lastRow As Long
    firstRow = 2
    lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row
     
    ' Очистить любой существующий вывод
    Sheet1.Range("H:L").ClearContents
     
    ' Отслеживать выходной ряд
    Dim outRow As Long
    outRow = 1
     
    Dim i As Long, marks As Long, rowSubject As String
    ' Прочитать данные
    For i = firstRow To lastRow
        marks = Sheet1.Range("C" & i).Value
        rowSubject = Sheet1.Range("D" & i).Value
        If rowSubject = subject Then
            ' Запишите данные студента, если предмет Геометрия
            Sheet1.Range("A" & i & ":" & "D" & i).Copy
            Sheet1.Range("H" & outRow).PasteSpecial xlPasteValues
             
            ' Запишите Зачет или Незачет
            If marks < 40 Then
                Sheet1.Range("L" & outRow).Value = "Незачет"
            ElseIf marks >= 40 Then
                Sheet1.Range("L" & outRow).Value = "Зачет"
            End If
            ' Переместить вывод в следующую строку
            outRow = outRow + 1
        End If
         
    Next i
     
End Sub

In Excel VBA, IF Then Else statement allows you to check for a condition, and perform an action accordingly.

This is extremely valuable in many situations as we will see in the examples later in this tutorial.

To give you a simple example, suppose you have a list of grades in Excel and you want to highlight all those students who have scored an A. Now, if I ask you to do this manually, you will check each student’s grade and if it’s an A, you’ll highlight it, and if it isn’t, then you’ll leave it as is.

The same logic can be built in VBA using the If Then Else statement as well (and of course do a lot more than just highlighting grades).

In this tutorial, I’ll show you different ways the ‘If Then Else’ construct can be used in Excel VBA, and some practical examples in action.

But before I get into the specifics, let me give you the syntax of the ‘IF Then Else’ statement.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

Syntax – IF Then Else

Below is the generic syntax of If Then Else construct in VBA

IF condition Then true_code [Else false_code]

Or

IF condition Then
true_code
Else
false_code
End IF

Note that the Else part of this statement is optional.

Now if you’re wondering what’s the difference between the two syntaxes, let me clarify.

The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement.

However, in the second syntax, the true_code part is in the second line. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines.

When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends.

Hence you need to use the End IF statement.

In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”

IF Then Else in VBA- Block IF without End If error

Examples of Using IF Then Statement in VBA

To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial).

Suppose you have a student’s score in cell A1 and you want to check whether the student passed the exam or not (passing marks threshold being 35).

Then you can use the following code:

Sub CheckScore()
If Range("A1").Value >=35 Then MsgBox "Pass"
End Sub

The above code has a single line of IF statement that checks the value in cell A1.

If it’s more than 35, it shows the message – “Pass”.

If it’s less than 35, nothing happens.

But what if you want to show a message in both the cases, whether a student passed or failed the exam.

The below code would do this:

Sub CheckScore()
If Range("A1").Value >= 35 Then
MsgBox "Pass"
Else
MsgBox "Fail"
End If
End Sub

The above code uses the IF as well as the ELSE statement to execute two different conditions. When the score is more than (or equal to) 35, the IF condition is true, and the code right below it gets executed (everything before the Else statement).

But when the IF condition is FALSE, the code jumps to the Else part and executes the code block in it.

Note that when we use a single line of IF Then statement, we don’t need to use End IF. But when we split it into more than one line, we need to use the End If statement.

Nested IF Then (Multiple IF Then statements)

So far we have used a single IF Then statement.

In case you have multiple conditions to check, you can use:

  • Multiple IF conditions
  • If Then Else statement
  • IF Then ElseIf Else construct

Let me show you how these differ and how to use this in Excel VBA.

Multiple IF Then Statements

Let’s take the same example of using a student’s score.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’.

We can use the below code to get this done:

Sub CheckScore()
If Range("A1").Value < 35 Then MsgBox "Fail"
If Range("A1").Value >= 35 Then MsgBox "Pass"
End Sub

You can use multiple IF Then statement as shown above. While this works, it’s not an example of good coding (as you will see the alternatives below).

In case you decide to use this, remember that these statements should either be independent or mutually exclusive. The important thing to know here is that in the above construct, all the IF statements are evaluated and the ones where the condition is true, the code is executed.

So even if the first IF statement is correct, the second would still be evaluated.

IF Then Else Statement

Suppose this time, instead of just displaying the message Pass/Fail, we have one more condition.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

We can use the below code to get this done:

Sub CheckScore()
If Range("A1").Value < 35 Then
MsgBox "Fail"
Else
If Range("A1").Value < 80 Then
MsgBox "Pass"
Else
MsgBox "Pass, with Distinction"
End If
End If
End Sub

In the above code, we have used multiple IF statements (nested IF Then) with the help of Else.

So there is an ‘IF Then Else’ construct within an ‘IF Then Else’ construct. This type of nesting allows you to check for multiple conditions and run the relevant block of code.

IF Then ElseIf Else Statement

The above code (that we saw in the previous section) can be further optimized by using the ElseIf statement.

Here is what we’re trying to do – If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

Sub CheckScore()
If Range("A1").Value < 35 Then
MsgBox "Fail"
ElseIf Range("A1").Value < 80 Then
MsgBox "Pass"
Else
MsgBox "Pass, with Distinction"
End If
End Sub

The above code uses ElseIf, which allows us to keep all the conditions within one single IF Then statement.

Using AND and OR in IF Then Else

So far in this tutorial, we have only checked for a single condition at a time.

However, when you have multiple dependent conditions, you can use the AND or OR statement with the IF conditions.

Below is the syntax of using AND/OR condition with the IF Then statement.

IF Condition1 AND Condition2 Then
true_code
Else
false_code
End IF

In the above code, only when both Condition1 and Condition2 are met, the true_code is executed. Even if one of the conditions is false, it will execute the false_code.

With OR, even if one of the conditions are true, it will execute the true_code. Only when all the conditions are false, it executes the false_code.

Now let’s see how AND and OR statement work with the IF Then Else construct.

Suppose you have the scores for two subjects instead of one, and you want to check for the following conditions:

  • Fail – When the score is less than 35 in any of the subjects.
  • Pass – When the score is more than or equal to 35, but less than 80 in both the subjects.
  • Pass, with Distinction – When the score is more than 35 in both the subjects and is more than or equal to 80 in one or both the subjects.

Here is the code that will do this:

Sub CheckScore()
If Range("A1").Value < 35 Or Range("B1").Value < 35 Then
MsgBox "Fail"
ElseIf Range("A1").Value < 80 And Range("B1").Value < 80 Then
MsgBox "Pass"
Else
MsgBox "Pass, with Distinction"
End If
End Sub

The above code uses both OR and AND statements.

You can also write this same code with a slight change (using OR instead of AND).

Sub CheckScore()
If Range("A1").Value < 35 Or Range("B1").Value < 35 Then
MsgBox "Fail"
ElseIf Range("A1").Value > 80 Or Range("B1").Value > 80 Then
MsgBox "Pass, with Distinction"
Else
MsgBox "Pass"
End If
End Sub

Both the above VBA codes will give you the same result. Personally, I prefer the first one as it has a logical flow of checking the scores (but that’s just me).

Using Not Equal to in If Then

In all the examples above, we have used the conditions that check whether a value equal to a specified value or not.

You can also use similar codes when checking when the value is not equal to a specified value in the VBA code. Not equal to represented by <> the Excel VBA.

To see a practical example of using <>, have a look at Example 1 below.

Using If Then Else with Loops in VBA

So far, we have been going through some examples that are good to understand how the ‘IF-THEN’ statements work in VBA, however, are not useful in the practical world.

If I need to grade students, I can easily do that using Excel functions.

So let’s have a look at some useful and practical examples that can help you automate some stuff and be more efficient.

Example 1 – Save and Close All Workbooks Except The Active Workbook

If you have a lot of workbooks open and you quickly want to close all, except the active workbook, you can use the below code,

Sub SaveCloseAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
On error resume next
If wb.Name <> ActiveWorkbook.Name Then
wb.Save
wb.Close
End If
Next wb
End Sub

The above code would save and close all the workbooks (except the active one).

It uses the For Next loop to go through the collection of all the open workbooks and checks the name using the IF condition.

If the name is not the same as that of the Active workbook, it saves and closes it.

In case there is a VBA code in any of the workbooks and you haven’t saved it as .xls or .xlsm, you will see a warning (as the vba codes are lost when you save it in .xlsx format).

Example 2 – Highlight Cells with Negative Values

Suppose that you have a column full of numbers and you want to quickly highlight all the cells with negative values in red, you can do that using the below code.

Sub HighlightNegativeCells()
Dim Cll As Range
For Each Cll In Selection
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
Cll.Font.Color = vbWhite
End If
Next Cll
End Sub

The above code uses the For Each loop and checks each cell in the selection that you have made. If the cell has a value that is negative, it’s highlighted in red with white font color.

Example 3 – Hide All the Worksheet Except the Current Worksheet

In case you want to quickly hide all the worksheets except the active one, you can use the below code:

Sub HideAllExceptActiveSheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> ActiveSheet.Name Then ws.Visible = xlSheetHidden
Next ws
End Sub

The above code uses the For Each loop to go through a collection of worksheets. It checks the name of each worksheet and hides it if it’s not the active worksheet.

Example 4 – Extract the Numeric Part from an Alphanumeric String

If you have alphanumeric strings in cells and you want to extract the numeric part from it, you can do that using the below code:

Function GetNumeric(CellRef As String)
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)
Next i
GetNumeric = Result
End Function

This code will create a custom function in Excel that can use within the worksheet (just like a regular function).

If Then Else in VBA - Custom Function

Where to Put the VBA Code?

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VB editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.IF Then Else in Excel VBA - Developer Tab in ribbon
  2. Click on Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.Insert Module in Excel VBA
  5. Copy and paste the code in the module window.If Then Else VBA Loop - code in the Vb Editor

You May Also Like the Following Excel Tutorials:

  • How to Record a Macro in Excel.
  • Working with Cells and Ranges in Excel VBA.
  • Working with Worksheets in Excel VBA.
  • Working with Workbooks in Excel VBA.
  • Creating a Custom Function in Excel Using VBA.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • Excel VBA MsgBox
  • How to Run a Macro in Excel.
  • How to Create and Use an Excel Add-in.
  • Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
  • Useful Excel Macro Examples for VBA Beginners (Ready-to-use).
  • How to Use Excel VBA InStr Function (with practical EXAMPLES).

VBA Logical Operators: AND, OR, NOT

Let’s say you want to process a customer order. For that, you want to first check to see if the ordered product exists or not. If it does, you also want to check if the quantity on hand is enough. Logical operators come in handy in such cases. Logical operators are used to evaluate more than one condition.

The main Excel VBA logical operators AND, OR, NOT are listed in the table below:

S/N Operator Description Example Output
1 AND AND: This is used to combine more than one condition. If all the conditions are true, AND evaluates to true. If any of the condition is false, AND evaluates to false If true = true AND false = true THEN false
2 OR OR: This is used to combine more than one condition. If any of the conditions evaluate to true, OR returns true. If all of them are false, OR returns false If true = true OR true = false THEN true
3 NOT NOT: This one works like an inverse function. If the condition is true, it returns false, and if a condition is false, it returns true. If NOT (true) Then false

VBA Logical Operators Example Source Code

For the sake of simplicity, we will be comparing hard coded numbers.

Add ActiveX buttons to the sheet from the “Insert option.”

Set the properties as shown in the image below

VBA Logical Operators

VBA Logical Operators

The following table shows the properties that you need to change and the values that you need to update too.

S/N Control Property Value
1 CommandButton1 Name btnAND
Caption AND Operator (0 = 0)
2 CommandButton2 Name btnOR
Caption OR Operator (1 = 1) Or (5 = 0)
3 CommandButton3 Name btnNOT
Caption NOT Operator Not (0 = )

Add the following code to btnAND_Click

Private Sub btnAND_Click()
    If (1 = 1) And (0 = 0) Then
            MsgBox "AND evaluated to TRUE", vbOKOnly, "AND operator"
        Else
            MsgBox "AND evaluated to FALSE", vbOKOnly, "AND operator"
    End If
End Sub

VBA If AND Operator

  • “If (1 = 1) And (0 = 0) Then” the if statement uses the AND logical operator to combine two conditions (1 = 1) And (0 = 0). If both conditions are true, the code above ‘Else’ keyword is executed. If both conditions are not true, the code below ‘Else’ keyword is executed.

Add the following code to btnOR_Click

Private Sub btnOR_Click()
    If (1 = 1) Or (5 = 0) Then
            MsgBox "OR evaluated to TRUE", vbOKOnly, "OR operator"
        Else
            MsgBox "OR evaluated to FALSE", vbOKOnly, "OR operator"
    End If
End Sub

VBA If OR Operator

  • “If (1 = 1) Or (5 = 0) Then” the if statement uses the OR logical operator to combine two conditions (1 = 1) And (5 = 0). If any of the conditions is true, the code above Else keyword is executed. If both conditions are false, the code below Else keyword is executed.

Add the following code to btnNOT_Click

Private Sub btnNOT_Click()
    If Not (0 = 0) Then
            MsgBox "NOT evaluated to TRUE", vbOKOnly, "NOT operator"
        Else
            MsgBox "NOT evaluated to FALSE", vbOKOnly, "NOT operator"
    End If
End Sub

VBA If NOT Operator

  • “If Not (0 = 0) Then” the VBA If Not function uses the NOT logical operator to negate the result of the if statement condition. If the conditions is true, the code below ‘Else’ keyword is executed. If the condition is true, the code above Else keyword is executed.

Download Excel containing above code

Понравилась статья? Поделить с друзьями:
  • Excel vba if then else and or
  • Excel vba if textbox1
  • Excel vba if target column
  • Excel vba if sum of range
  • Excel vba if statements and