Vba excel оператор if not

Main 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. NOT operator negates the given statement. We use these logical operators with IF statements in our day to day data analysis. If we use IF NOT statement in VBA consider this as an inverse function.

We have discussed above that we use the logical operators with if statements. In this article, we will use NOT operator with the if statement. I said earlier that IF NOT statement in VBA is also considered as an inverse function. Why is that because if the condition is true it returns false and if the condition is false it returns true. Have a look below,

IF A>B equals to IF NOT B>A

Both the if statements above are identical how? In the first statement if A is greater than B then the next statement is executed and in the next, if not statement means if B is not greater than A which in itself means A is greater than B.

The most simple way to understand IF NOT statement should be as follows:

If True Then
If NOT false Then

Or we can say that

If False then
IF NOT True then

Both the statements in Comparison 1 and Comparison 2 are identical to each other.

Let’s use IF NOT function in few examples which will make it more clearly for us.

Note: We need to keep in mind that in order to use VBA in excel we first have to enable our developer’s tab from the files tab and then from the options section.

How to Use Excel VBA IF Not?

We will learn how to use a VBA IF Not with few examples in excel.

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

Example #1 – VBA IF Not

Follow the below steps to use IF NOT in Excel VBA.

For example, I have two values in sheet 1 in cell A1 and B1. Have a look at them below,

VBA IF NOT Example 1

What I want to do is compare these two values which one is greater using IF NOT statement in VBA.

Step 1: Go to the developer’s tab and then click on Visual Basic to open the VB Editor.

VBA IF NOT Example 1.1

Step 2: Insert a module from the insert tab in the VB Editor. Double click on the module we just inserted to open another window where we are going to write our code.

VBA IF NOT Module

Step 3: Every VBA code starts with a sub-function as below,

Code:

Sub Sample()

End Sub

VBA IF NOT Example 1.2

Step 4: Declare two variables as integers which will store our values from cell A1 and B1.

Code:

Sub Sample()

Dim A, B As Integer

End Sub

VBA IF NOT Example 1.3

Step 5: To assign values to these variables we need to activate the worksheet first by the following code.

Code:

Sub Sample()

Dim A, B As Integer
Worksheets("Sheet1").Activate

End Sub

VBA IF NOT Example 1.4

Step 6: Now we will assign these variables the values of A1 and B1.

Code:

Sub Sample()

Dim A, B As Integer
Worksheets("Sheet1").Activate
A = Range("A1")
B = Range("B1")

End Sub

VBA IF NOT Example 1.5

Step 7: Let us compare both the variables using IF NOT statement by the following code,

Code:

Sub Sample()

Dim A, B As Integer
Worksheets("Sheet1").Activate
A = Range("A1")
B = Range("B1")
If Not A > B Then
MsgBox "B is greater than A"
Else
MsgBox "A is greater than B"
End If

End Sub

VBA IF NOT Example 1.6

Step 8: Run the above code from the run button in VBA or we can press the F5 button to do the same. We will get the following result.

VBA IF ELSE 1

Step 9: Let us inverse the values of A and B and again run the code to see the following result.

VBA IF ELSE 2

In the first execution, A was greater than B but we compared IF NOT A>B, Initially, the condition was true so it displayed the result for False statement i.e. A is greater than B and vice versa for execution second.

Example #2 – VBA IF Not

In the first example we compared integers, let us compare strings in this example with IF NOT statement in VBA. In the same sheet1, we have two strings in cell A3 and B3 as follows,

VBA IF NOT Example 2.1

Let us compare both the strings using IF NOT Statement.

Step 1: To open VB Editor first click on Developer’s Tab and then click on Visual Basic.

VBA IF NOT Example 2.2

Step 2: In the same module, we inserted above double click on it to start writing the second code.

Module 2

Step 3: Declare a sub-function below the code we wrote first.

Code:

Sub Sample1()

End Sub

Sub Sample 1

Step 4: Declare two variables as a string that will store our values from cell A3 and B3.

Code:

Sub Sample1()

Dim A, B As String

End Sub

VBA (Dim A)

Step 5: To assign values to these variables we need to activate the worksheet first by the following code to use its properties.

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate

End Sub

Worksheets

Step 6: Now we will assign these variables the values of A3 and B3.

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")

End Sub

Range

Step 7: Let us compare both the variables using IF NOT statement by the starting the if statement as follows,

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")
If Not A = B Then

End Sub

Compare a and b

Step 8: If A = B condition is true then the above statement will negate it and return the value as false.

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")
If Not A = B Then
MsgBox "Both the strings are not same"

End Sub

Msgbox

Step 9: If both the strings are same i.e. if the result is returned as true display the following message,

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")
If Not A = B Then
MsgBox "Both the strings are not same"
Else
MsgBox "Both the Strings are same"
End If

End Sub

Else if

Step 10: Now let us run the above code by pressing the F5 button or from the run button given. Once we run the code we get the following result.

VBA IF ELSE 3

Step 11: Now let us make both the stings in A3 and B3 cell same to see the different result when we run the same code.

VBA IF ELSE 3 gif

In the first execution A was not similar to B but we compared IF NOT A=B, Initially the condition was true so it displayed the result for false statement i.e. both the strings are not same and when both of the strings were same we get the different message as both the strings are same.

Things to Remember

  • IF NOT is a comparison statement.
  • IF NOT negates the value of the condition i.e. if a condition is true it returns false and vice versa.
  • IF NOT statement is basically an inverse function.

Recommended Articles

This has been a guide to VBA If Not. Here we have discussed how to use Excel VBA If Not along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Active Cell
  2. VBA RGB
  3. VBA Transpose
  4. VBA Not

In VBA, when you use the IF statement, it executes a line of code if the condition you have specified to test is TRUE. But when you use the NOT operator with IF, it checks if the condition you have specified is not TRUE and executes the code based on that. It’s like making the IF statement opposite, TRUE into FALSE and FALSE into TRUE.

Let’s say you want to test if A < B, and if this condition is true IF will return TRUE, right? But when you use IF NOT A < B, it will return FALSE.

Note: NOT is a logical operator.

Examples to use VBA IF NOT

Here’s we will see a simple example to understand it:

Sub myMacro()

Dim A As Range, B As Range
Set A = Range("A1")
Set B = Range("B1")

If Not A < B Then
    MsgBox "A is not greater than B."
Else
    MsgBox "B is not greater than A."
End If
   
End Sub

In the above code, you have used the NOT operator to test whether B is not greater than the A.

If you look at the condition statement, you can understand the actual condition to test is if B is greater than A, but as we have used the NOT statement, it will return FALSE if the condition is TRUE.

Here’s another example that you can use to understand it.

Sub myMacro()

If Not ActiveSheet.Name = Sheets("Sheet1").Name Then
    Sheets("Sheet1").Activate
End If

End Sub

Now, in this code, you have used NOT with IF to see if the active sheet is Sheet1 or not, and if it is not, the line of code that we have specified will activate the Sheet1.

Logical functions are useful for calculations that require multiple conditions or criteria to test. In our earlier articles, we have seen “VBA IF,” “VBA OR,” and “VBA AND” conditions. This article will discuss the “VBA IF NOT” function. Before introducing VBA IF NOT function, let me show you about VBA NOT functionThe VBA NOT function in MS Office Excel VBA is a built-in logical function. If a condition is FALSE, it yields TRUE; otherwise, it returns FALSE. It works as an inverse function.read more first.

Table of contents
  • IF NOT in VBA
    • What is NOT Function in VBA?
    • Examples of NOT & IF Function in VBA?
      • Example #1
      • Example #2
    • NOT with IF Condition:
    • Recommended Articles

What is NOT Function in VBA?

The “NOT” function is one of our logical functions with Excel and VBA. All the logical functions require logical tests to perform and return TRUE if the logical test is correct. If the logical test is incorrect, it will return FALSE.

But “VBA NOT” is the opposite of the other logical function. So, we would say this is the inverse function of logical functions.

The “VBA NOT” function returns “FALSE” if the logical test is correct. If the logical test is incorrect, it will return “TRUE.” Now, look at the syntax of the “VBA NOT” function.

NOT(Logical Test)

It is very simple. First, we need to provide a logical test. Then, the NOT function evaluates the test and returns the result.

VBA-IF-NOT

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA IF NOT (wallstreetmojo.com)

Examples of NOT & IF Function in VBA?

Below are the examples of using the IF and NOT function in excelNOT Excel function is a logical function in Excel that is also known as a negation function and it negates the value returned by a function or the value returned by another logical function.read more VBA.

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

Example #1

Take a look at the below code for an example.

Code:

Sub NOT_Example()

  Dim k As String

  k = Not (100 = 100)

  MsgBox k

End Sub

In the above code, we have declared the variable as a string.

Dim k As String

Then, for this variable, we have assigned the NOT function with the logical test as 100 = 100.

k = Not (100 = 100)

Then, we have written the code to show the result in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more. MsgBox k

Now, we will execute the code and see the result.

VBA IF NOT Example 1

We got the result as “FALSE.”

Now, look back at 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. We have provided the logical test as 100 = 100, which is generally TRUE; since we had given the NOT function, we got the result as FALSE. As we said in the beginning, it gives inverse results compared to other logical functions. Since 100 equals 100, it has returned the result as FALSE.

Example #2

Now, we will look at one more example with different numbers.

Code:

Sub NOT_Example()

 Dim k As String

 k = Not (85 = 148)

 MsgBox k

End Sub

The code is the same. The only thing we have changed here is We have changed the logical test from 100 = 100 to 85 = 148.

Now, we will run the code and see what the result is.

Example 2

This time we got the result as TRUE. Now, examine the logical test.

k = Not (85 = 148)

We all know 85 is not equal to the number 148. Since it is not equal, the NOT function has returned the result as TRUE.

NOT with IF Condition:

In Excel or VBA, logical conditions are incomplete without the combination IF condition. Using the IF condition in excelIF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
read more
we can do many more things beyond default TRUE or FALSE. For example, we got FALSE and TRUE default results in the above examples. Instead, we can modify the result in our own words.

Look at the below code.

Code:

Sub NOT_Example2()

  Dim Number1 As String
  Dim Number2 As String

  Number1 = 100
  Number2 = 100

  If Not (Number1 = Number2) Then
   MsgBox "Number 1 is not equal to Number 2"
  Else
   MsgBox "Number 1 is equal to Number 2"
  End If

End Sub

We have declared two variables.

Dim Number1 As String & Dim Number2 As String

For these two variables, we have assigned the numbers 100 and 100, respectively.

Number1 = 100 & Number2 = 100

Then, we have attached the IF condition to alter the default TRUE or FALSE for the NOT function. If the result of the NOT function is TRUE, then my result will be as follows.

MsgBox “Number 1 is not equal to Number 2.”

If the NOT function result is FALSE, my result is as follows.

MsgBox “Number 1 is equal to Number 2.”

Now, we will run the code and see what happens.

VBA IF NOT Example 3

We got the result as “Number 1 is equal to Number 2”, so the NOT function has returned the FALSE result to the IF condition. So, the IF condition returned this result.

Like this, we can use the IF condition to do the inverse test.

Recommended Articles

This article has been a guide to VBA IF NOT. Here, we discuss using the IF and NOT function in Excel VBA, examples, and downloadable Excel templates. Below are some useful articles related to VBA: –

  • VBA Replace String
  • VBA If Else Statement
  • VBA AND Function
  • IF OR in VBA

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

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

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

  • VBA ЕСЛИ НЕ

VBA ЕСЛИ НЕ

На любом языке программирования у нас есть логические операторы И ИЛИ и НЕ. У каждого оператора есть определенная функция. AND объединяет два или более операторов и возвращает значения true, если каждое из утверждений истинно, где находится в операторе OR, если любое из утверждений истинно, значение истинно. Оператор НЕ — это другое. Оператор NOT отрицает данное утверждение. Мы используем эти логические операторы с операторами IF в нашем повседневном анализе данных. Если мы используем оператор IF NOT в VBA, рассмотрим это как обратную функцию.

Выше мы обсуждали, что мы используем логические операторы с операторами if. В этой статье мы будем использовать оператор NOT с оператором if. Ранее я говорил, что оператор IF NOT в VBA также рассматривается как обратная функция. Почему, потому что, если условие истинно, оно возвращает ложь, а если условие ложно, оно возвращает истину. Посмотрите ниже,

ЕСЛИ A> B равно IF НЕ B> A

Оба предложения if выше идентичны, как? В первом операторе, если A больше, чем B, выполняется следующий оператор, а в следующем, если не оператор, означает, что B не больше, чем A, что само по себе означает, что A больше, чем B.

Самый простой способ понять утверждение IF NOT должно быть следующим:

 Если верно, то если не ложно, то 

Или мы можем сказать, что

 Если Ложь, тогда ЕСЛИ НЕ Верно 

Оба утверждения в Сравнении 1 и Сравнении 2 идентичны друг другу.

Давайте использовать функцию IF NOT в нескольких примерах, которые сделают ее более понятной для нас.

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

Как использовать Excel VBA, если нет?

Мы научимся использовать VBA IF Not с несколькими примерами в Excel.

Вы можете скачать этот VBA, если не шаблон Excel здесь — VBA, если не шаблон Excel

Пример № 1 — VBA, если нет

Выполните следующие шаги, чтобы использовать ЕСЛИ НЕ в Excel VBA.

Например, у меня есть два значения на листе 1 в ячейках A1 и B1. Посмотрите на них ниже,

То, что я хочу сделать, это сравнить эти два значения, которое больше, используя оператор IF NOT в VBA.

Шаг 1: Перейдите на вкладку разработчика и нажмите Visual Basic, чтобы открыть редактор VB.

Шаг 2: Вставьте модуль из вкладки вставки в VB Editor. Дважды щелкните по модулю, который мы только что вставили, чтобы открыть другое окно, в которое мы собираемся написать наш код.

Шаг 3: Каждый код VBA начинается с подфункции, как показано ниже,

Код:

 Sub Sample () End Sub 

Шаг 4: Объявите две переменные как целые числа, которые будут хранить наши значения из ячеек A1 и B1.

Код:

 Sub Sample () Dim A, B As Integer End Sub 

Шаг 5: Чтобы присвоить значения этим переменным, нам нужно сначала активировать лист с помощью следующего кода.

Код:

 Sub Sample () Dim A, B As Integer Worksheets ("Sheet1"). Активировать End Sub 

Шаг 6: Теперь мы присвоим этим переменным значения A1 и B1.

Код:

 Sub Sample () Dim A, B As Integer Worksheets ("Sheet1"). Активировать A = Range ("A1") B = Range ("B1") End Sub 

Шаг 7: Давайте сравним обе переменные, используя оператор IF NOT с помощью следующего кода:

Код:

 Sub Sample () Dim A, B As Integer Worksheets ("Sheet1"). Активируйте A = Range ("A1") B = Range ("B1") Если не A> B, то MsgBox "B больше, чем A" Иначе MsgBox «A больше, чем B» End If End Sub 

Шаг 8: Запустите приведенный выше код с кнопки запуска в VBA, или мы можем нажать кнопку F5, чтобы сделать то же самое. Мы получим следующий результат.

Шаг 9: Давайте инвертируем значения A и B и снова запустим код, чтобы увидеть следующий результат.

В первом выполнении A было больше, чем B, но мы сравнивали IF NOT A> B, изначально условие было истинным, поэтому оно отображало результат для оператора False, т. Е. A больше, чем B, и наоборот для второго выполнения.

Пример № 2 — VBA, если нет

В первом примере мы сравнили целые числа, давайте сравним строки в этом примере с оператором IF NOT в VBA. В том же листе 1 у нас есть две строки в ячейках A3 и B3 следующим образом:

Давайте сравним обе строки, используя оператор IF NOT.

Шаг 1: Чтобы открыть VB Editor, сначала нажмите вкладку разработчика, а затем нажмите Visual Basic.

Шаг 2: В тот же модуль, который мы вставили выше, дважды щелкните по нему, чтобы начать писать второй код.

Шаг 3: Объявите подфункцию под кодом, который мы написали первым.

Код:

 Sub Sample1 () End Sub 

Шаг 4: Объявите две переменные в виде строки, в которой будут храниться наши значения из ячеек A3 и B3.

Код:

 Sub Sample1 () Dim A, B As String End Sub 

Шаг 5: Чтобы присвоить значения этим переменным, нам нужно сначала активировать лист с помощью следующего кода, чтобы использовать его свойства.

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активировать End Sub 

Шаг 6: Теперь мы присвоим этим переменным значения A3 и B3.

Код:

 Sub Sample1 () Dim A, B As String Worksheet ("Sheet1"). Активировать A = диапазон ("A3") B = диапазон ("B3") End Sub 

Шаг 7: Давайте сравним обе переменные, используя оператор IF NOT, начав оператор if следующим образом:

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активируйте A = Range ("A3") B = Range ("B3"), если не A = B, тогда End Sub 

Шаг 8: Если условие A = B является истинным, то приведенное выше утверждение отрицает его и возвращает значение как ложное.

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активируйте A = Range ("A3") B = Range ("B3") Если не A = B, то MsgBox "Обе строки не совпадают" Конец Sub 

Шаг 9: Если обе строки одинаковы, т. Е. Если результат возвращен как true, отобразите следующее сообщение,

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активируйте A = Range ("A3") B = Range ("B3") Если не A = B, то MsgBox "Обе строки не одинаковы" Иначе MsgBox "Обе строки одинаковы" End If End Sub 

Шаг 10: Теперь давайте запустим приведенный выше код, нажав кнопку F5 или указанную кнопку запуска. Запустив код, мы получим следующий результат.

Шаг 11: Теперь давайте сделаем одинаковые строки в ячейках A3 и B3, чтобы увидеть разные результаты при выполнении одного и того же кода.

В первом исполнении A не было похоже на B, но мы сравнивали IF NOT A = B, изначально условие было истинным, поэтому оно отображало результат для ложного утверждения, т. Е. Обе строки не совпадают, и когда обе строки были одинаковыми, мы получаем разные сообщения, так как обе строки одинаковы.

То, что нужно запомнить

  • ЕСЛИ НЕ является сравнительным утверждением.
  • Если NOT отрицает значение условия, то есть если условие истинно, оно возвращает ложь, и наоборот.
  • Если оператор NOT является в основном обратной функцией.

Рекомендуемые статьи

Это было руководство для VBA, если нет. Здесь мы обсудили, как использовать Excel VBA If Not вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Работа с VBA Active Cell
  2. Удаление строки в VBA
  3. Как использовать Excel VBA Transpose?
  4. Как исправить ошибку 1004 с помощью VBA
  5. VBA не


You can use the following basic syntax to use IF NOT logic in VBA to test if some condition is not met:

Sub IfNot()
    Dim i As Integer
    
    For i = 2 To 11
        If Not Range("B" & i) = "West" Then
        Result = "Not West"
        Else
        Result = "West"
        End If
    Range("C" & i) = Result
    Next i

End Sub

This particular example checks if each cell in the range B2:B12 is not equal to “West” and then assigns either “Not West” or “West” to each corresponding cell in the range C2:C12.

The following example shows how to use this syntax in practice.

Example: How to Use IF NOT in VBA

Suppose we have the following dataset in Excel that shows the team name and division of various basketball teams:

Suppose we would like to assign a value of “West” or “Not West” to each cell in column C based on whether or not each team belongs to the West division or not.

We can create the following macro to do so:

Sub IfNot()
    Dim i As Integer
    
    For i = 2 To 11
        If Not Range("B" & i) = "West" Then
        Result = "Not West"
        Else
        Result = "West"
        End If
    Range("C" & i) = Result
    Next i

End Sub

When we run this macro, we receive the following output:

The values in column C tell us whether or not each division in column B is equal to “West” or not.

For example:

  • Team A belongs to the “West” so column C displays “West”
  • Team B belongs to the “East ” so column C displays “Not West”
  • Team C belongs to the “East ” so column C displays “Not West”
  • Team D belongs to the “North” so column C displays “Not West”

And so on.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

VBA: How to Use IF OR to Test Multiple Conditions
VBA: How to Use IF AND to Test Multiple Conditions
VBA: How to Check if String Contains Another String


Return to VBA Code Examples

In this Article

  • IF…AND
  • IF…OR
  • IF NOT…

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:

vba if and

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

Sub CheckProfit()
   If Range("C5") >= 10000 And Range("C6") < 5000 Then
      MsgBox "$5,000 profit achieved!"
   Else
      Msgbox "Profit not achieved!"
   End If
End Sub

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.

vba if and msg

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

vba if and else

IF…OR

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.

Sub CheckProfit()
   If Range("C5") > 10000 Or Range("C6") < 5000 Then
      MsgBox "$5,000 profit achieved!"
   Else
      Msgbox "Profit not achieved!"
   End If
End Sub

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

vba if or

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.

Sub CheckProfit() 
If NOT Range("C5")< 10000 Or Range("C6") < 5000 Then 
   MsgBox "$5,000 profit achieved!" 
Else 
   Msgbox "Profit not achieved!" 
End If 
End Sub

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:

IF Range("C5") > 10000

and this this line of code:

IF NOT Range("C5") < 10000

are testing for the same thing!

This post provides a complete guide to the VBA If Statement in VBA. If you are looking for the syntax then check out the quick guide in the first section which includes some examples.

The table of contents below provides an overview of what is included in the post. You use this to navigate to the section you want or you can read the post from start to finish.

“Guess, if you can, and choose, if you dare.” – Pierre Corneille

Quick Guide to the VBA If Statement

Description Format Example
If Then If [condition is true] Then
    [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
End If
If Else If [condition is true] Then
    [do something]
Else
    [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
Else
       Debug.Print «Try again»
End If
If ElseIf If [condition 1 is true] Then
    [do something]
ElseIf [condition 2 is true] Then
    [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
ElseIf score > 50 Then
       Debug.Print «Passed»
ElseIf score <= 50 Then
       Debug.Print «Try again»
End If
Else and ElseIf
(Else must come
after ElseIf’s)
If [condition 1 is true] Then
      [do something]
ElseIf [condition 2 is true] Then
      [do something]
Else
      [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
ElseIf score > 50 Then
       Debug.Print «Passed»
ElseIf score > 30 Then
       Debug.Print «Try again»
Else
       Debug.Print «Yikes»
End If
If without Endif
(One line only)
If [condition is true] Then [do something] If value <= 0 Then value = 0

The following code shows a simple example of using the VBA If statement

If Sheet1.Range("A1").Value > 5 Then
    Debug.Print "Value is greater than five."
ElseIf Sheet1.Range("A1").Value < 5 Then
    Debug.Print "value is less than five."
Else
    Debug.Print "value is equal to five."
End If

The Webinar

Members of the Webinar Archives can access the webinar for this article by clicking on the image below.

(Note: Website members have access to the full webinar archive.)

What is the VBA If Statement

The VBA If statement is used to allow your code to make choices when it is running.

You will often want to make choices based on the data your macros reads.

For example, you may want to read only the students who have marks greater than 70. As you read through each student you would use the If Statement to check the marks of each student.

The important word in the last sentence is check. The If statement is used to check a value and then to perform a task based on the results of that check.

The Test Data and Source Code

We’re going to use the following test data for the code examples in this post:

VBA If Sample Data

You can download the test data with all the source code for post plus the solution to the exercise at the end:

Format of the VBA If-Then Statement

The format of the If Then statement is as follows

If [condition is true] Then

The If keyword is followed by a Condition and the keyword Then

Every time you use an If Then statement you must use a matching End If statement.
When the condition evaluates to true, all the lines between If Then and End If are processed.

If [condition is true] Then
    [lines of code]
    [lines of code]
    [lines of code]
End If

To make your code more readable it is good practice to indent the lines between the If Then and End If statements.

Indenting Between If and End If

Indenting simply means to move a line of code one tab to the right. The rule of thumb is to indent between start and end statements like

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

To indent the code you can highlight the lines to indent and press the Tab key. Pressing Shift + Tab will Outdent the code i.e. move it one tab to the left.

You can also use the icons from the Visual Basic Toolbar to indent/outdent the code

VBA If

Select code and click icons to indent/outdent

If you look at any code examples on this website you will see that the code is indented.

A Simple If Then Example

The following code prints out the names of all students with marks greater than 50 in French.

' https://excelmacromastery.com/
Sub ReadMarks()
    
    Dim i As Long
    ' Go through the marks columns
    For i = 2 To 11
        ' Check if marks greater than 50
        If Sheet1.Range("C" & i).Value > 50 Then
            ' Print student name to the Immediate Window(Ctrl + G)
            Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value
        End If
    
    Next
    
End Sub

Results
Bryan Snyder
Juanita Moody
Douglas Blair
Leah Frank
Monica Banks

Play around with this example and check the value or the > sign and see how the results change.

Using Conditions with the VBA If Statement

The piece of code between the If and the Then keywords is called the condition. A condition is a statement that evaluates to true or false. They are mostly used with Loops and If statements. When you create a condition you use signs like >,<,<>,>=,<=,=.

The following are examples of conditions

Condition This is true when
x < 5 x is less than 5
x <= 5 x is less than or equal to 5
x > 5 x is greater than 5
x >= 5 x is greater than or equal to 5
x = 5 x is equal to 5
x <> 5 x does not equal 5
x > 5 And x < 10 x is greater than 5 AND x is less than 10
x = 2 Or x >10 x is equal to 2 OR x is greater than 10
Range(«A1») = «John» Cell A1 contains text «John»
Range(«A1») <> «John» Cell A1 does not contain text «John»

You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.

When equals is used in a condition it means “is the left side equal to the right side”.

The following table demonstrates how the equals sign is used in conditions and assignments

Using Equals Statement Type Meaning
Loop Until x = 5 Condition Is x equal to 5
Do While x = 5 Condition Is x equal to 5
If x = 5 Then Condition Is x equal to 5
For x = 1 To 5 Assignment Set the value of x to 1, then to 2 etc.
x = 5 Assignment Set the value of x to 5
b = 6 = 5 Assignment and Condition Assign b to the result of condition 6 = 5
x = MyFunc(5,6) Assignment Assign x to the value returned from the function

The last entry in the above table shows a statement with two equals. The first equals sign is the assignment and any following equals signs are conditions.

This might seem confusing at first but think of it like this. Any statement that starts with a variable and an equals is in the following format

[variable] [=] [evaluate this part]

So whatever is on the right of the equals sign is evaluated and the result is placed in the variable. Taking the last three assignments again, you could look at them like this

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

Using ElseIf with the VBA If Statement

The ElseIf statement allows you to choose from more than one option. In the following example we print for marks that are in the Distinction or High Distinction range.

' https://excelmacromastery.com/
Sub UseElseIf()
    
    If Marks >= 85 Then
        Debug.Print "High Destinction"
    ElseIf Marks >= 75 Then
        Debug.Print "Destinction"
    End If
    
End Sub

The important thing to understand is that order is important. The If condition is checked first.
If it is true then “High Distinction” is printed and the If statement ends.
If it is false then the code moves to the next ElseIf and checks it condition.

Let’s swap around the If and ElseIf from the last example. The code now look like this

' https://excelmacromastery.com/
Sub UseElseIfWrong()
    
    ' This code is incorrect as the ElseIf will never be true
    If Marks >= 75 Then
        Debug.Print "Destinction"
    ElseIf Marks >= 85 Then
        ' code will never reach here
        Debug.Print "High Destinction"
    End If
    
End Sub

In this case we check for a value being over 75 first. We will never print “High Distinction” because if a value is over 85 is will trigger the first if statement.

To avoid these kind of problems we should use two conditions. These help state exactly what you are looking for a remove any confusion. The example below shows how to use these. We will look at more multiple conditions in the section below.

If marks >= 75 And marks < 85 Then
    Debug.Print "Destinction"
ElseIf marks >= 85 And marks <= 100 Then
    Debug.Print "High Destinction"
End If

Let’s expand the original code. You can use as many ElseIf statements as you like. We will add some more to take into account all our mark classifications.

If you want to try out these examples you can download the code from the top of this post.

Using Else With the VBA If Statement

The VBA Else statement is used as a catch all. It basically means “if no conditions were true” or “everything else”. In the previous code example, we didn’t include a print statement for a fail mark. We can add this using Else.

' https://excelmacromastery.com/
Sub UseElse()
    
    If Marks >= 85 Then
        Debug.Print "High Destinction"
    ElseIf Marks >= 75 Then
        Debug.Print "Destinction"
    ElseIf Marks >= 55 Then
        Debug.Print "Credit"
    ElseIf Marks >= 40 Then
        Debug.Print "Pass"
    Else
        ' For all other marks
        Debug.Print "Fail"
    End If
    
End Sub

So if it is not one of the other types then it is a fail.

Let’s write some code to go through our sample data and print the student and their classification:

' https://excelmacromastery.com/
Sub AddClass()
    
    ' get the last row
    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

    ' Go through the marks columns
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Check marks and classify accordingly
        If Marks >= 85 Then
            sClass = "High Destinction"
        ElseIf Marks >= 75 Then
            sClass = "Destinction"
        ElseIf Marks >= 55 Then
            sClass = "Credit"
        ElseIf Marks >= 40 Then
            sClass = "Pass"
        Else
            ' For all other marks
            sClass = "Fail"
        End If
    
        ' Write out the class to column E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

The results look like this with column E containing the classification of the marks

VBA If ElseIf Class

Results

Remember that you can try these examples for yourself with the code download from the top of this post.

Using Logical Operators with the VBA If Statement

You can have more than one condition in an If Statement. The VBA keywords And and Or allow use of multiple conditions.

These words work in a similar way to how you would use them in English.

Let’s look at our sample data again. We now want to print all the students that got over between 50 and 80 marks.
We use And to add an extra condition. The code is saying: if the mark is greater than or equal 50 and less than 75 then print the student name.

' https://excelmacromastery.com/
Sub CheckMarkRange()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Store marks for current student
        marks = Sheet1.Range("C" & i).Value
        
        ' Check if marks greater than 50 and less than 75
        If marks >= 50 And marks < 80 Then
             ' Print first and last name to Immediate window(Ctrl G)
             Debug.Print Sheet1.Range("A" & i).Value & Sheet1.Range("B" & i).Value
        End If
    
    Next

End Sub

Results
Douglas Blair
Leah Frank
Monica Banks

In our next example we want the students who did History or French. So in this case we are saying if the student did History OR if the student did French:

' Description: Uses OR to check the study took History or French.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub UseOr()
    
    ' Get the data range
    Dim rg As Range
    Set rg = shMarks.Range("A1").CurrentRegion

    Dim i As Long, subject As String
    
    ' Read through the data
    For i = 2 To rg.Rows.Count
    
        ' Get the subject
        subject = rg.Cells(i, 4).Value
        
        ' Check if subject greater than 50 and less than 80
        If subject = "History" Or subject = "French" Then
            ' Print first name and subject to Immediate window(Ctrl G)
            Debug.Print rg.Cells(i, 1).Value & " " & rg.Cells(i, 4).Value
        End If
    
    Next
    
End Sub

Results
Bryan History
Bradford French
Douglas History
Ken French
Leah French
Rosalie History
Jackie History

Using Multiple conditions like this is often a source of errors. The rule of thumb to remember is to keep them as simple as possible.

Using If And

The AND works as follows

Condition 1 Condition 2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

What you will notice is that AND is only true when all conditions are true

Using If Or

The OR keyword works as follows

Condition 1 Condition 2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

What you will notice is that OR is only false when all the conditions are false.

Mixing AND and OR together can make the code difficult to read and lead to errors. Using parenthesis can make the conditions clearer.

' https://excelmacromastery.com/
Sub OrWithAnd()
    
 Dim subject As String, marks As Long
 subject = "History"
 marks = 5
    
 If (subject = "French" Or subject = "History") And marks >= 6 Then
     Debug.Print "True"
 Else
     Debug.Print "False"
 End If
    
End Sub

Using If Not

There is also a NOT operator. This returns the opposite result of the condition.

Condition Result
TRUE FALSE
FALSE TRUE

The following two lines of code are equivalent.

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

as are

If True Then 
If Not False Then 

and

If False Then 
If Not True Then 

Putting the condition in parenthesis makes the code easier to read

If Not (marks >= 40) Then

A common usage of Not when checking if an object has been set. Take a worksheet for example. Here we declare the worksheet

Dim mySheet As Worksheet
' Some code here

We want to check mySheet is valid before we use it. We can check if it is nothing.

If mySheet Is Nothing Then

There is no way to check if it is something as there is many different ways it could be something. Therefore we use Not with Nothing

If Not mySheet Is Nothing Then

If you find this a bit confusing you can use parenthesis like this

If Not (mySheet Is Nothing) Then

The IIF function

Note that you can download the IIF examples below and all source code from the top of this post.

VBA has an fuction similar to the Excel If function. In Excel you will often use the If function as follows:

=IF(F2=””,””,F1/F2)

The format is

=If(condition, action if true, action if false).

VBA has the IIf statement which works the same way. Let’s look at an example. In the following code we use IIf to check the value of the variable val. If the value is greater than 10 we print true otherwise we print false:

' Description: Using the IIF function to check a number.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub CheckNumberIIF()
 
    Dim result As Boolean
    Dim number As Long
    
    ' Prints True
    number = 11
    result = IIf(number > 10, True, False)
    Debug.Print "Number " & number & " greater than 10 is " & result
    
    ' Prints false
    number = 5
    result = IIf(number > 10, True, False)
    Debug.Print "Number " & number & " greater than 10 is " & result
    
End Sub

In our next example we want to print out Pass or Fail beside each student depending on their marks. In the first piece of code we will use the normal VBA If statement to do this:

' https://excelmacromastery.com/
Sub CheckMarkRange()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Store marks for current student
        marks = Sheet1.Range("C" & i).Value
        
        ' Check if student passes or fails
        If marks >= 40 Then
             ' Write out names to to Column F
             Sheet1.Range("E" & i) = "Pass"
        Else
             Sheet1.Range("E" & i) = "Fail"
        End If
    
    Next

End Sub

In the next piece of code we will use the IIf function. You can see that the code is much neater here:

' Description: Using the IIF function to check marks.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub CheckMarkRange()

    ' Get the data range
    Dim rg As Range
    Set rg = shMarks.Range("A1").CurrentRegion
    
    Dim i As Long, marks As Long, result As String
    ' Go through the marks columns
    For i = 2 To rg.Rows.Count
        
        ' Store marks for current student
        marks = rg.Cells(i, 3).Value
        
        ' Check if student passes or fails
        result = IIf(marks >= 40, "Pass", "Fail")
        
        ' Print the name and result
        Debug.Print rg.Cells(i, 1).Value, result
    
    Next

End Sub

You can see the IIf function is very useful for simple cases where you are dealing with two possible options.

Using Nested IIf

You can also nest IIf statements like in Excel. This means using the result of one IIf with another. Let’s add another result type to our previous examples. Now we want to print Distinction, Pass or Fail for each student.

Using the normal VBA we would do it like this

' https://excelmacromastery.com/
Sub CheckResultType2()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Store marks for current student
        marks = Sheet1.Range("C" & i).Value
        
        If marks >= 75 Then
             Sheet1.Range("E" & i).Value = "Distinction"
        ElseIf marks >= 40 Then
             ' Write out names to to Column F
             Sheet1.Range("E" & i).Value = "Pass"
        Else
             Sheet1.Range("E" & i).Value = "Fail"
        End If
    
    Next

End Sub

Using nested IIfs we could do it like this:

' Description: Using a nested IIF function to check marks.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub UsingNestedIIF()

    ' Get the data range
    Dim rg As Range
    Set rg = shMarks.Range("A1").CurrentRegion
    
    Dim i As Long, marks As Long, result As String
    ' Go through the marks columns
    For i = 2 To rg.Rows.Count
        
        marks = rg.Cells(i, 3).Value
        result = IIf(marks >= 55, "Credit", IIf(marks >= 40, "Pass", "Fail"))
        
        Debug.Print marks, result
    
    Next i

End Sub

Using nested IIf is fine in simple cases like this. The code is simple to read and therefore not likely to have errors.

What to Watch Out For

It is important to understand that the IIf function always evaluates both the True and False parts of the statement regardless of the condition.

In the following example we want to divide by marks when it does not equal zero. If it equals zero we want to return zero.

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

However, when marks is zero the code will give a “Divide by zero” error. This is because it evaluates both the True and False statements. The False statement here i.e. (60 / Marks) evaluates to an error because marks is zero.

If we use a normal IF statement it will only run the appropriate line.

marks = 0
If marks = 0 Then
    'Only executes this line when marks is zero
    total = 0
Else
    'Only executes this line when marks is Not zero
    total = 60 / marks
End If

What this also means is that if you have Functions for True and False then both will be executed. So IIF will run both Functions even though it only uses one return value. For example

'Both Functions will be executed every time
total = IIf(marks = 0, Func1, Func2)

(Thanks to David for pointing out this behaviour in the comments)

If Versus IIf

So which is better?

You can see for this case that IIf is shorter to write and neater. However if the conditions get complicated you are better off using the normal If statement. A disadvantage of IIf is that it is not well known so other users may not understand it as well as code written with a normal if statement.

Also as we discussed in the last section IIF always evaluates the True and False parts so if you are dealing with a lot of data the IF statement would be faster.

My rule of thumb is to use IIf when it will be simple to read and doesn’t require function calls. For more complex cases use the normal If statement.

Using Select Case

The Select Case statement is an alternative way to write an If statment with lots of ElseIf’s. You will find this type of statement in most popular programming languages where it is called the Switch statement. For example Java, C#, C++ and Javascript all have a switch statement.

The format is

Select Case [variable]
    Case [condition 1]
    Case [condition 2]
    Case [condition n]
    Case Else
End Select

Let’s take our AddClass example from above and rewrite it using a Select Case statement.

' https://excelmacromastery.com/
Sub AddClass()
    
    ' get the last row
    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

    ' Go through the marks columns
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Check marks and classify accordingly
        If Marks >= 85 Then
            sClass = "High Destinction"
        ElseIf Marks >= 75 Then
            sClass = "Destinction"
        ElseIf Marks >= 55 Then
            sClass = "Credit"
        ElseIf Marks >= 40 Then
            sClass = "Pass"
        Else
            ' For all other marks
            sClass = "Fail"
        End If
    
        ' Write out the class to column E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

The following is the same code using a Select Case statement. The main thing you will notice is that we use “Case 85 to 100” rather than “marks >=85 And marks <=100”.

' https://excelmacromastery.com/
Sub AddClassWithSelect()
    
    ' get the first and last row
    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

    ' Go through the marks columns
    For i = firstRow To lastRow
        marks = Sheet1.Range("C" & i).Value
        ' Check marks and classify accordingly
        Select Case marks
        Case 85 To 100
            sClass = "High Destinction"
        Case 75 To 84
            sClass = "Destinction"
        Case 55 To 74
            sClass = "Credit"
        Case 40 To 54
            sClass = "Pass"
        Case Else
            ' For all other marks
            sClass = "Fail"
        End Select
        ' Write out the class to column E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Using Case Is

You could rewrite the select statement in the same format as the original ElseIf. You can use Is with Case.

' https://excelmacromastery.com/
Select Case marks
    Case Is >= 85
         sClass = "High Destinction"
    Case Is >= 75
        sClass = "Destinction"
    Case Is >= 55
        sClass = "Credit"
    Case Is >= 40
        sClass = "Pass"
    Case Else
        ' For all other marks
        sClass = "Fail"
End Select

You can use Is to check for multiple values. In the following code we are checking if marks equals 5, 7 or 9.

' https://excelmacromastery.com/
Sub TestMultiValues()
    
    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

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Понравилась статья? Поделить с друзьями:
  • Vba excel открыть гиперссылку
  • Vba excel открыть все книги в папке
  • Vba excel открыть word документ
  • Vba excel открыть chrome
  • Vba excel отключить пересчет формул