Vba excel оператор условия

На чтение 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

Однострочная и многострочная конструкции оператора If…Then…Else и функция IIf, используемые в коде VBA Excel — синтаксис, компоненты, примеры.

Оператор If…Then…Else предназначен для передачи управления одному из блоков операторов в зависимости от результатов проверяемых условий.

Однострочная конструкция

Оператор If…Then…Else может использоваться в однострочной конструкции без ключевых слов Else, End If.

Синтаксис однострочной конструкции If…Then…

If [условие] Then [операторы]

Компоненты однострочной конструкции If…Then…

  • условие — числовое или строковое выражение, возвращающее логическое значение True или False;
  • операторы — блок операторов кода VBA Excel, который выполняется, если компонент условие возвращает значение True.

Если компонент условие возвращает значение False, блок операторов конструкции If…Then… пропускается и управление программой передается следующей строке кода.

Пример 1

Sub Primer1()

Dim d As Integer, a As String

d = InputBox(«Введите число от 1 до 20», «Пример 1», 1)

   If d > 10 Then a = «Число « & d & » больше 10″

MsgBox a

End Sub

Многострочная конструкция

Синтаксис многострочной конструкции If…Then…Else

If [условие] Then

[операторы]

ElseIf [условие] Then

[операторы]

Else

[операторы]

End If

Компоненты многострочной конструкции If…Then…Else:

  • условие — числовое или строковое выражение, следующее за ключевым словом If или ElseIf и возвращающее логическое значение True или False;
  • операторы — блок операторов кода VBA Excel, который выполняется, если компонент условие возвращает значение True;
  • пунктирная линия обозначает дополнительные структурные блоки из строки ElseIf [условие] Then и строки [операторы].

Если компонент условие возвращает значение False, следующий за ним блок операторов конструкции If…Then…Else пропускается и управление программой передается следующей строке кода.

Самый простой вариант многострочной конструкции If…Then…Else:

If [условие] Then

[операторы]

Else

[операторы]

End If

Пример 2

Sub Primer2()

Dim d As Integer, a As String

d = InputBox(«Введите число от 1 до 40», «Пример 2», 1)

   If d < 11 Then

      a = «Число « & d & » входит в первую десятку»

   ElseIf d > 10 And d < 21 Then

      a = «Число « & d & » входит во вторую десятку»

   ElseIf d > 20 And d < 31 Then

      a = «Число « & d & » входит в третью десятку»

   Else

      a = «Число « & d & » входит в четвертую десятку»

   End If

MsgBox a

End Sub

Функция IIf

Функция IIf проверяет заданное условие и возвращает значение в зависимости от результата проверки.

Синтаксис функции

IIf([условие], [если True], [если False])

Компоненты функции IIf

  • условие — числовое или строковое выражение, возвращающее логическое значение True или False;
  • если True — значение, которое возвращает функция IIf, если условие возвратило значение True;
  • если False — значение, которое возвращает функция IIf, если условие возвратило значение False.

Компоненты если True и если False могут быть выражениями, значения которых будут вычислены и возвращены.

Пример 3

Sub Primer3()

Dim d As Integer, a As String

Instr:

On Error Resume Next

d = InputBox(«Введите число от 1 до 20 и нажмите OK», «Пример 3», 1)

If d > 20 Then GoTo Instr

    a = IIf(d < 10, d & » — число однозначное», d & » — число двузначное»)

MsgBox a

End Sub

Пример 4
Стоит отметить, что не зависимо от того, выполняется условие или нет, функция IIf вычислит оба выражения в параметрах если True и если False:

Sub Primer4()

On Error GoTo Instr

Dim x, y

x = 10

y = 5

    MsgBox IIf(x = 10, x + 5, y + 10)

    MsgBox IIf(x = 10, x + 5, y / 0)

Exit Sub

Instr:

MsgBox «Произошла ошибка: « & Err.Description

End Sub


При нажатии кнопки «Cancel» или закрытии крестиком диалогового окна InputBox из первых двух примеров, генерируется ошибка, так как в этих случаях функция InputBox возвращает пустую строку. Присвоение пустой строки переменной d типа Integer вызывает ошибку. При нажатии кнопки «OK» диалогового окна, числа, вписанные в поле ввода в текстовом формате, VBA Excel автоматически преобразует в числовой формат переменной d. В третьем примере есть обработчик ошибок.


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

Наиболее важные операторы условия, используемые в Excel VBA – это операторы If … Then и Select Case. Оба этих выражения проверяют одно или несколько условий и, в зависимости от результата, выполнят различные действия. Далее мы поговорим об этих двух операторах условия подробнее.

Оператор «If … Then» в Visual Basic

Оператор If … Then проверяет условие и, если оно истинно (TRUE), то выполняется заданный набор действий. Также может быть определён набор действий, которые должны быть выполнены, если условие ложно (FALSE).

Синтаксис оператора If … Then вот такой:

If Условие1 Then
   Действия в случае, если выполняется Условие1
ElseIf Условие2 Then
   Действия в случае, если выполняется Условие2
Else
   Действия в случае, если не выполнено ни одно из Условий
End If

В этом выражении элементы ElseIf и Else оператора условия могут не использоваться, если в них нет необходимости.

Ниже приведён пример, в котором при помощи оператора If … Then цвет заливки активной ячейки изменяется в зависимости от находящегося в ней значения:

If ActiveCell.Value < 5 Then
   ActiveCell.Interior.Color = 65280  'Ячейка окрашивается в зелёный цвет
ElseIf ActiveCell.Value < 10 Then
   ActiveCell.Interior.Color = 49407  'Ячейка окрашивается в оранжевый цвет
Else
   ActiveCell.Interior.Color = 255  'Ячейка окрашивается в красный цвет
End If

Обратите внимание, что как только условие становится истинным, выполнение условного оператора прерывается. Следовательно, если значение переменной ActiveCell меньше 5, то истинным становится первое условие и ячейка окрашивается в зелёный цвет. После этого выполнение оператора If … Then прерывается и остальные условия не проверяются.

Более подробно о применении в VBA условного оператора If … Then можно узнать на сайте Microsoft Developer Network.

Оператор «Select Case» в Visual Basic

Оператор Select Case схож с оператором If … Then в том, что он также проверяет истинность условия и, в зависимости от результата, выбирает один из вариантов действий.

Синтаксис оператора Select Case вот такой:

Select Case Выражение
Case Значение1
   Действия в случае, если результат Выражения соответствует Значению1
Case Значение2
   Действия в случае, если результат Выражения соответствует Значению2

Case Else
   Действия в случае, если результат Выражения не соответствует ни одному из перечисленных вариантов Значения
End Select

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

В следующем примере при помощи конструкции Select Case изменяется цвет заливки текущей ячейки в зависимости от находящегося в ней значения:

Select Case ActiveCell.Value
   Case Is <= 5
      ActiveCell.Interior.Color = 65280  'Ячейка окрашивается в зелёный цвет
   Case 6, 7, 8, 9
      ActiveCell.Interior.Color = 49407  'Ячейка окрашивается в оранжевый цвет
   Case 10
      ActiveCell.Interior.Color = 65535  'Ячейка окрашивается в жёлтый цвет
   Case 11 To 20
      ActiveCell.Interior.Color = 10498160  'Ячейка окрашивается в лиловый цвет
   Case Else
      ActiveCell.Interior.Color = 255  'Ячейка окрашивается в красный цвет
End Select

В приведённом выше примере показано, как можно различными способами задать значение для элемента Case в конструкции Select Case. Вот эти способы:

Case Is <= 5 Таким образом при помощи ключевого слова Case Is можно проверить, удовлетворяет ли значение Выражения условию вида <=5.
Case 6, 7, 8, 9 Так можно проверить, совпадает ли значение Выражения с одним из перечисленных значений. Перечисленные значения разделяются запятыми.
Case 10 Так проверяется, совпадает ли значение Выражения с заданным значением.
Case 11 To 20 Таким образом можно записать выражение для проверки, удовлетворяет ли значение Выражения условию вида от 11 до 20 (эквивалентно неравенству «11<=значение<=20»).
Case Else Вот так, при помощи ключевого слова Else, указываются действия для того случая, если значение Выражения не соответствует ни одному из перечисленных вариантов Case.

Как только одно из условий будет найдено, выполняются соответствующие действия и производится выход из конструкции Select Case. То есть в любом случае будет выполнена только одна из перечисленных ветвей Case.

Более подробную информацию о работе VBA оператора Select Case можно найти на сайте Microsoft Developer Network.

Оцените качество статьи. Нам важно ваше мнение:

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 If
  • ElseIF — несколько условий
  • Еще
  • Если еще
  • Вложенные IF
  • ЕСЛИ — Или, И, Xor, Не
  • Если сравнения
  • Если петли
  • Если остальные примеры
  • VBA If, ElseIf, Else в Access VBA

Если то

Операторы If в VBA позволяют проверять, являются ли выражения ИСТИННЫМИ или ЛОЖНЫМИ, выполняя другой код в зависимости от результатов.Давайте посмотрим на простой пример:

1 Если Range («a2»). Value> 0, то Range («b2»). Value = «Positive»

Это проверяет, больше ли значение в диапазоне A2, чем 0. Если да, установите для диапазона B2 значение «Положительный».Примечание: при тестировании условий мы будем использовать операторы сравнения =,>, <,, =. Подробнее о них мы поговорим позже в статье.Вот синтаксис простого однострочного оператора If:

1 Если [test_expression], то [действие]

Чтобы упростить чтение, вы можете использовать символ продолжения строки (подчеркивание), чтобы расширить операторы If до двух строк (как мы это сделали на рисунке выше):

12 Если [test_expression], то _[действие]
12 Если Range («a2»). Value> 0 Then _Диапазон («b2»). Значение = «Положительное»

Конец, если

Приведенный выше «однострочный» оператор if хорошо работает, когда вы проверяете одно условие. Но по мере того, как ваши операторы IF усложняются с несколькими условиями, вам нужно будет добавить «End If» в конец оператора if:

123 Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»Конец, если

Вот синтаксис:

123 Если [test_expression], то[действие]Конец, если

End If означает конец оператора if.

Теперь давайте добавим ElseIF:

ElseIF — несколько условий

ElseIf добавляется к существующему оператору If. ElseIf проверяет выполнение условия ТОЛЬКО если предыдущие условия не были выполнены.В предыдущем примере мы проверили, положительное ли значение ячейки. Теперь мы также проверим, является ли значение ячейки отрицательным с помощью ElseIf:

12345 Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ElseIf Range («a2»). Значение <0 ТогдаДиапазон («b2»). Значение = «Отрицательное»Конец, если

Вы можете использовать несколько ElseIf для проверки нескольких условий:

1234567891011 Sub If_Multiple_Conditions ()Если Range («a2»). Value = «Cat», тоДиапазон («b2»). Значение = «Мяу»ElseIf Range («a2»). Value = «Dog» ТогдаДиапазон («b2»). Значение = «Гав»ElseIf Range («a2»). Value = «Duck» ТогдаДиапазон («b2»). Значение = «Кряк»Конец, еслиКонец подписки

Теперь мы добавим Еще:

Еще

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

Мы закончим наш пример, используя Else, чтобы указать, что если значение ячейки не является положительным или отрицательным, то оно должно быть равно нулю:

1234567 Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ElseIf Range («a2»). Значение <0 ТогдаДиапазон («b2»). Значение = «Отрицательное»ЕщеДиапазон («b2»). Значение = «Ноль»Конец, если

Если еще

Самый распространенный тип оператора If — это простой If-Else:

1234567 Sub If_Else ()Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ЕщеДиапазон («b2»). Значение = «Не положительное»Конец, еслиКонец подписки

Вложенные IF

Вы также можете «вкладывать» операторы if друг в друга.

1234567891011 Sub Nested_Ifs ()Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ЕщеЕсли Range («a2»). Value <0 ThenДиапазон («b2»). Значение = «Отрицательное»ЕщеДиапазон («b2»). Значение = «Ноль»Конец, еслиКонец, еслиКонец подписки

ЕСЛИ — Или, И, Xor, Не

Далее мы обсудим логические операторы: Or, And, Xor, Not.

Я для

В Или оператор проверяет, если как минимум одно условие выполнено.

Следующий код проверяет, является ли значение в диапазоне A2 меньше 5000 или больше 10000:

123 Если Диапазон («a2»). Значение 10000 ТогдаДиапазон («b2»). Значение = «Вне диапазона»Конец, если

Вы можете включить несколько Ор в одну строку:

123 Если Диапазон («a2»). Значение 10000 Или Диапазон («a2»). Значение = 9999 ТогдаДиапазон («b2»). Значение = «Вне диапазона»Конец, если

Если вы собираетесь использовать несколько OR, рекомендуется использовать символ продолжения строки, чтобы облегчить чтение кода:

123456 Если Диапазон («a2»). Значение <5000 или _Диапазон («a2»). Значение> 10000 или _Диапазон («a2»). Значение = 9999 ТогдаДиапазон («b2»). Значение = «Вне диапазона»Конец, если

Если и

Оператор And позволяет проверить, ВСЕ условия соблюдены.

123 Если Range («a2»). Value> = 5000 And Range («a2»). Value <= 10000 ThenДиапазон («b2»). Значение = «В диапазоне»Конец, если

Если Xor

Оператор Xor позволяет проверить, выполняется ровно одно условие. Если соблюдаются нулевые условия, Xor вернет FALSE, если два или более условий выполнены, Xor также вернет false.

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

Если не

Оператор Not используется для преобразования FALSE в TRUE или TRUE в FALSE:

123 Sub IF_Not ()MsgBox Not (True)Конец подписки

Обратите внимание, что для переключения оператора Not требуется скобка, заключающая выражение.

Оператор Not также может применяться к операторам If:

123 Если нет (Диапазон («a2»). Значение> = 5000 и диапазон («a2»). Значение <= 10000), тоДиапазон («b2»). Значение = «Вне диапазона»Конец, если

Если сравнения

При сравнении обычно используется один из операторов сравнения:

Оператор сравнения Объяснение
= Равно
Не равно
> Больше чем
>= Больше или равно
< Меньше, чем
<= Меньше или равно

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

Если — логическая функция

При построении выражений для операторов If вы также можете использовать любую функцию, которая генерирует TRUE или False. VBA имеет несколько из этих функций:

Функция Описание
IsDate Возвращает ИСТИНА, если выражение является допустимой датой.
Пустой Проверьте наличие пустых ячеек или неопределенных переменных
IsError Проверить значения ошибок
Нулевой Проверить значение NULL
IsNumeric Проверить числовое значение

Их можно назвать так:

1 Если IsEmpty (Range («A1»). Value), то MsgBox «Cell Empty»

В Excel также есть много дополнительных функций, которые можно вызывать с помощью WorksheetFunction. Вот пример функции Excel IsText:

12 Если Application.WorksheetFunction.IsText (Range («a2»). Value), то _MsgBox «Ячейка — это текст»

Вы также можете создавать свои собственные определяемые пользователем функции (UDF). Ниже мы создадим простую логическую функцию, возвращающую ИСТИНА. Затем мы вызовем эту функцию в нашем операторе If:

1234567891011 Sub If_Function ()Если TrueFunction, тоMsgBox «True»Конец, еслиКонец подпискиФункция TrueFunction () как логическое значениеTrueFunction = TrueКонечная функция

Сравнение текста

Вы также можете сравнить текст, аналогично сравнению чисел:

Сравнивая текст, вы должны помнить о «регистре» (верхний или нижний). По умолчанию VBA считает буквы с разными регистрами несоответствующими. Другими словами, «А» «а».Если вы хотите, чтобы VBA игнорировал регистр, вы должны добавить объявление Option Compare Text в верхнюю часть модуля:

После этого объявления «А» = «а»:

12345 Вариант Сравнить текстSub If_Text ()MsgBox «a» = «A»Конец подписки

VBA, если нравится

Оператор Like VBA позволяет проводить неточные сравнения текста. Щелкните ссылку «Like Operator», чтобы узнать больше, но мы покажем базовый пример ниже:

12345678 Dim strName as StringstrName = «Мистер Чарльз»Если strName Like «Mr *» ТогдаMsgBox «True»ЕщеMsgBox «False»Конец, если

Здесь мы используем подстановочный знак звездочки «*». * Обозначает любое количество любых символов. Таким образом, приведенный выше оператор If вернет ИСТИНА. Оператор Like — чрезвычайно мощный, но часто недостаточно используемый инструмент для работы с текстом.

Если петли

Циклы VBA позволяют повторять действия. Комбинирование IF-ELSE с циклами — отличный способ быстро обработать многие вычисления.

Продолжая наш пример Положительного / Отрицательного, мы добавим цикл For Each Loop для перебора диапазона ячеек:

1234567891011121314 Sub If_Loop ()Тусклая ячейка как диапазонДля каждой ячейки в диапазоне («A2: A6»)Если Cell.Value> 0, тоCell.Offset (0, 1) .Value = «Положительный»ElseIf Cell.Value <0 ТогдаCell.Offset (0, 1) .Value = «Отрицательное»ЕщеCell.Offset (0, 1) .Value = «Ноль»Конец, еслиСледующая ячейкаКонец подписки

Если остальные примеры

Теперь перейдем к более конкретным примерам.

Проверить, пуста ли ячейка

Этот код проверяет, пуста ли ячейка. Если он пуст, он проигнорирует ячейку. Если он не пустой, он выведет значение ячейки в ячейку справа:

1234567 Sub If_Cell_Empty ()Если Range («a2»). Value «» ThenДиапазон («b2»). Значение = Диапазон («a2»). ЗначениеКонец, еслиКонец подписки

Проверьте, содержит ли ячейка определенный текст

Функция Instr проверяет, найдена ли строка текста в другой строке. Используйте его с оператором If, чтобы проверить, содержит ли ячейка определенный текст:

123 Если Instr (Range («A2»). Value, «text»)> 0, тоMsgbox «Текст найден»Конец, если

Проверить, содержит ли ячейка текст

Этот код проверит, является ли ячейка текстом:

1234567 Sub If_Cell_Is_Text ()Если Application.WorksheetFunction.IsText (Range («a2»). Value), тоMsgBox «Ячейка — это текст»Конец, еслиКонец подписки

Если Goto

Вы можете использовать результат оператора If, чтобы «перейти к» другому разделу кода.

12345678910 Sub IfGoTo ()Если IsError (Cell.value), тоПерейти к пропускуКонец, если’Некоторый кодПропускать:Конец подписки

Удалить строку, если ячейка пуста

Используя If и циклы, вы можете проверить, пуста ли ячейка, и, если да, удалить всю строку.

123456789 Sub DeleteRowIfCellBlank ()Тусклая ячейка как диапазонДля каждой ячейки в диапазоне («A2: A10»)Если Cell.Value = «» Тогда Cell.EntireRow.DeleteСледующая ячейкаКонец подписки

Если MessageBox Да / Нет

С помощью окон сообщений VBA вы можете попросить пользователя выбрать один из нескольких вариантов. Окно сообщения Да / Нет предлагает пользователю выбрать Да или Нет. Вы можете добавить Окно сообщения Да / Нет в процедуру, чтобы спросить пользователя, хотят ли они продолжить выполнение процедуры или нет. Вы обрабатываете ввод пользователя с помощью оператора If.Вот окно сообщения Да / Нет на практике:

123456789101112 Sub MsgBoxVariable ()Тусклый ответ как целое числоanswer = MsgBox («Продолжить?», vbQuestion + vbYesNo)Если answer = vb Да ТогдаMsgBox «Да»ЕщеMsgBox «Нет»Конец, еслиКонец подписки

VBA If, ElseIf, Else в Access VBA

Функции If, ElseIf и Else в Access VBA работают точно так же, как и в Excel VBA.

Вы можете использовать оператор If, чтобы проверить, есть ли записи в наборе записей.

In VBA, the if is a decision-making statement that is used to execute a block of code if a certain condition is true. For example, if you have a message box in the application and the user is presented with the “Yes, No, and Cancel” options.

You may execute different actions based on the user’s selection upon selecting Yes, No, or Cancel. By using If statement, you may capture the user’s option and evaluate in the If..ElseIf..Then..Else statements and execute different code for each case.

See the next section for learning how to use the If, ElseIf..Else statements, followed by examples including using if statement with Microsoft Excel.

Structure of VBA If statements

Following is the general syntax of using If, Else If, and Else VBA statements.

Using a single line:

If condition Then [ statements_to_be_executed] [ Else [ else_statements_to_Execute ] ]

  • In single-line syntax, you have two separate blocks of codes. One, if the expression is evaluated as true. In that case, the statements inside the if statement execute.
  • If the condition is false, the statements in the Else part will execute.

Multi-line syntax:

If condition [ Then ] 

[ statements_to_Execute ] 

[ ElseIf elseifcondition [ Then ] 

[ elseif_statements_to_execute ] ] 

[ Else 

[ else_statements_to_Execute] ] 

End If

  • First of all, the expression is tested in the first If condition.
  • If the condition was false at first if statement, the ElseIf part is tested. You may use multiple ElseIf statements if your application has more options.
  • If all conditions are False, the statement(s) in the Else part will execute.

Let us now look at how to use the If..ElseIf..Else statements in VBA and excel.

First, a simple if statement example

Let me start with the basic example where just the If VBA statement is used without Else in a single line. A simple message box is displayed if the condition is True:

Private Sub if_exmamples()

‘Single line if statement

numx = 15

If numx = 15 Then MsgBox «The value of numx=15: True»

End Sub

As you run this code, a message box should appear because of the value of variable numx = 15.

Using If with Else statement in a single line

Let me now add the Else VBA statement in the above example in single line If statement. The variable value is now set as 20, so the condition becomes false and Else part should execute. Have a look at the code and output:

Private Sub if_exmamples()

‘Single line if with Else Statement

numx = 20

If numx = 15 Then MsgBox «The condition is True» Else MsgBox «The value is not = 15, so False!»

End Sub

VBA if else

You can see, the Else part message box displayed as the condition was false.

Using ElseIf statement with If..Else example

Let us move ahead by using the ElseIf statement. The scenario is, we have a three buttons dialog box with Yes/No and Cancel options. As a button is pressed by the user, we will get the button value and display a respective message to the user that tells which button was pressed.

For that, the VBA Else If statement is as used as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Function ElseIf_exmample()

btnVal = MsgBox(«Press a button and program will tell which button was pressed?», 3, «Demo of If..ElseIf..Else»)

If btnVal = 6 Then

MsgBox «User pressed Yes!»

ElseIf btnVal = 7 Then

MsgBox «User Pressed No!»

Else

MsgBox «User Pressed Cancel!»

End If

End Function

VBA if ElseIf Else

You see, how btnVal variable is evaluated in the If and ElseIf statements and then we displayed the respective message to the user by another dialog.

Using If..ElseIf..Else with excel

In this example, the If..ElseIf..Else statements are used with Microsoft Excel. For that, an ActiveX button is placed in the worksheet. In the click event of the button, the code with If..ElseIf..Else is written to check the value in cell A1.

Upon clicking the button, If the value in A1 is 0, the B1 cell will be updated by “Sunday” text. Similarly, 1 for Monday, 2 for Tuesday, and so on.

The example code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

Private Sub dayName_Click()

Dim readValue As Integer

readValue = Range(«A1»).Value

If readValue = 0 Then

Range(«B1»).Value = «Sunday»

ElseIf readValue = 1 Then

Range(«B1»).Value = «Monday»

ElseIf readValue = 2 Then

Range(«B1»).Value = «Tuesday»

ElseIf readValue = 3 Then

Range(«B1»).Value = «Wednesday»

ElseIf readValue = 4 Then

Range(«B1»).Value = «Thursday»

ElseIf readValue = 5 Then

Range(«B1»).Value = «Friday»

Else

Range(«B1»).Value = «Saturday»

End If

End Sub

The result:

VBA if Excel

An example of Excel VBA If..Else with And operator

If you have multiple expressions to check in the If statement and all have to be True in order to execute the code, you may do this by using the ‘And’ operator. By that, you may use two or more expressions. See the following example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Private Sub if_and_Click()

Dim color1 As String, color2 As String

color1 = Range(«A1»).Value

color2 = Range(«B1»).Value

If color1 = «Green» And color2 = «White» Then

Range(«C1»).Value = «Yellow»

Else

Range(«C1»).Value = «Black»

End If

End Sub

VBA if and Excel

You noticed I entered Green in A1 and White in B1 and the output is written as Yellow in C1. If any of the values did not match (A1 or B1) then the if part would have been evaluated as False and Else was updated the C1 with Black. See the graphic below:

if and false

An example of If..Else with Or operator

If you require to evaluate multiple expressions and execute the If block if any of the expressions is True, then you may use the ‘Or’ operator. This is unlike the ‘And’ operator where all expressions have to be True.

To make things clearer, I am amending the above example just a little bit – replacing ‘And’ by ‘Or’ operator in the If statement. In the excel cells, the same text is given as in the second graphic i.e. A1=Green and B1=Red and see the output:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Private Sub if_or_Click()

Dim color1 As String, color2 As String

color1 = Range(«A1»).Value

color2 = Range(«B1»).Value

If color1 = «Green» Or color2 = «White» Then

Range(«C1»).Value = «Yellow»

Else

Range(«C1»).Value = «Black»

End If

End Sub

if or

An example of If with Not operator

See the use of Not operator in the example below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Private Sub if_not_Click()

Dim color1 As String

color1 = Range(«A1»).Value

If Not color1 = «Red» Then

Range(«B1»).Value = «Brown»

Else

Range(«B1»).Value = «Green»

End If

End Sub

The result as I entered Yellow:

if not

As I entered the Red, the outcome:

if not false

This is because the if condition became false.

Принятие решений позволяет программистам контролировать поток выполнения сценария или одного из его разделов. Исполнение управляется одним или несколькими условными операторами.

Содержание:

  • If…Then — Если То
  • Синтаксис
  • Диаграмма потока
  • пример
  • if..else заявление
  • Синтаксис
  • Диаграмма потока
  • пример
  • if … elseif..else statement
  • Синтаксис
  • Диаграмма потока
  • пример
  • вложенные операторы if
  • Синтаксис
  • пример
  • инструкция switch
  • Синтаксис
  • пример

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

Решения, условия, алгоритмы if, then, switch в VBA Excel

VBA предоставляет следующие типы решений. Нажмите следующие ссылки, чтобы проверить их данные.

Оператор If состоит из логического выражения, за которым следуют одно или несколько операторов. Если условие называется Истинным, выполняются утверждения в условии If (s). Если условие называется False, выполняются инструкции после цикла If.

Синтаксис

Ниже приведен синтаксис оператора If в VBScript.

If(boolean_expression) Then
   Statement 1
   .....
   .....
   Statement n
End If

Диаграмма потока

Решения, условия, алгоритмы if, then, switch в VBA Excel

пример

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

Private Sub if_demo_Click()
   Dim x As Integer
   Dim y As Integer
    
   x = 234
   y = 32
    
   If x > y Then
      MsgBox "X is Greater than Y"
   End If
End Sub

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

X is Greater than Y

Если заявление состоит из логического выражения следует один или более операторов.

if..else заявление

Оператор If состоит из логического выражения, за которым следуют одно или несколько операторов. Если условие называется Истинным, выполняются утверждения в условии If (s). Если условие называется False, выполняются утверждения в разделе Else Part.

Синтаксис

Ниже приведен синтаксис оператора If Else в VBScript.

If(boolean_expression) Then
   Statement 1
   .....
   .....
   Statement n
Else
   Statement 1
   .....
   ....
   Statement n
End If

Диаграмма потока

Решения, условия, алгоритмы if, then, switch в VBA Excel

пример

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

Private Sub if_demo_Click()
   Dim x As Integer
   Dim y As Integer
    
   x = 234
   y = 324
    
   If x > y Then
      MsgBox "X is Greater than Y"
   Else
      Msgbox "Y is Greater than X"
   End If
End Sub

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

Y is Greater than X

Если иное утверждение состоит из логического выражения следует один или более операторов. Если условие равно True, выполняются инструкции в операторах If . Если условие ложно, выполняется Else часть скрипта.

if … elseif..else statement

Оператор If, за которым следует один или несколько инструкций ElseIf, которые состоят из булевых выражений, а затем следуют инструкции else по умолчанию, которая выполняется, когда все условие становится ложным.

Синтаксис

Ниже приведен синтаксис оператора If Elseif-Else в VBScript.

If(boolean_expression) Then
   Statement 1
   .....
   .....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
   .....
   ....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
   .....
   ....
   Statement n
Else
   Statement 1
   .....
   ....
   Statement n
End If

Диаграмма потока

Решения, условия, алгоритмы if, then, switch в VBA Excel

пример

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

Private Sub if_demo_Click()
   Dim x As Integer
   Dim y As Integer
    
   x = 234
   y = 234
    
   If x > y Then
      MsgBox "X is Greater than Y"
   ElseIf y > x Then
      Msgbox "Y is Greater than X"
   Else
      Msgbox "X and Y are EQUAL"
   End If
End Sub

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

X and Y are EQUAL

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

вложенные операторы if

Оператор If или ElseIf внутри другого оператора If или ElseIf. Внутренние операторы If выполняются на основе внешних операторов If. Это позволяет VBScript легко справляться с сложными условиями.

Синтаксис

Ниже приведен синтаксис инструкции Nested If в VBScript.

If(boolean_expression) Then
   Statement 1
   .....
   .....
   Statement n
   
   If(boolean_expression) Then
      Statement 1
      .....
      .....
      Statement n
   ElseIf (boolean_expression) Then
      Statement 1
      .....
      ....
      Statement n
   Else
      Statement 1
      .....
      ....
      Statement n
   End If
Else
   Statement 1


   Statement n
End If

пример

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

Private Sub nested_if_demo_Click()
   Dim a As Integer
   a = 23
  
   If a > 0 Then
      MsgBox "The Number is a POSITIVE Number"
      
      If a = 1 Then
         MsgBox "The Number is Neither Prime NOR Composite"
      ElseIf a = 2 Then
         MsgBox "The Number is the Only Even Prime Number"
      ElseIf a = 3 Then
         MsgBox "The Number is the Least Odd Prime Number"
      Else
         MsgBox "The Number is NOT 0,1,2 or 3"
      End If
   ElseIf a < 0 Then
      MsgBox "The Number is a NEGATIVE Number"
   Else
      MsgBox "The Number is ZERO"
   End If
End Sub

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

The Number is a POSITIVE Number
The Number is NOT 0,1,2 or 3

Если или ElseIf заявление внутри другого, если или ELSEIF заявление.

инструкция switch

Когда пользователь хочет выполнить группу операторов в зависимости от значения выражения, используется случай переключения. Каждое значение называется случаем, и переменная включается в зависимости от каждого случая. Оператор Case Else выполняется, если тестовое выражение не соответствует ни одному из случаев, указанным пользователем.

Case Else — необязательный оператор в Select Case, однако для хорошей практики программирования всегда есть оператор Case Else.

Синтаксис

Ниже приведен синтаксис оператора Switch в VBScript.

Select Case expression
   Case expressionlist1
      statement1
      statement2
      ....
      ....
      statement1n
   Case expressionlist2
      statement1
      statement2
      ....
      ....
   Case expressionlistn
      statement1
      statement2
      ....
      ....   
   Case Else
      elsestatement1
      elsestatement2
      ....
      ....
End Select

пример

Для демонстрационной цели найдем тип целого с помощью функции.

Private Sub switch_demo_Click()
   Dim MyVar As Integer
   MyVar = 1
  
   Select Case MyVar
      Case 1
         MsgBox "The Number is the Least Composite Number"
      Case 2
         MsgBox "The Number is the only Even Prime Number"
      Case 3
         MsgBox "The Number is the Least Odd Prime Number"
      Case Else
         MsgBox "Unknown Number"
   End Select
End Sub

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

The Number is the Least Composite Number

Переключатель заявление позволяет переменной быть проверены на равенство в отношении списка значений.

 С уважением, авторы сайта Компьютерапия

Понравилась статья? Поделитесь ею с друзьями и напишите отзыв в комментариях!

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