Vba excel if with or without you

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:

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

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:

Comparing Text

You can also compare text similar to comparing numbers:

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:

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

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:

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:

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:

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:

Check if cell contains text

This code will test if a cell is text:

If Goto

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

Delete Row if Cell is Blank

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 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 Code Examples Add-in

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

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

Источник

Else without if ошибка vba

Канал в Telegram

Вы здесь

Работа с условием If в VBA

Условный оператор IF является основной частью любого языка программирования. Без него не обойтись при написании даже небольшой программы, в которой необходимо принять некоторое решение. Синтаксис конструкции If следующий:

If условие Then [Команда 1] [Else Команда 2]

Если перевести, то получается: Если условие Тогда Команда 1 Иначе Команда 2

Т.е. если условие истинно тогда выполняется некоторая Команда (Команды) иначе выполняются другие Команды.В этом варианте конструкции IF будет выполнено только одна Команда. Else можно пропустить.

Примечание: При такой форме условия в Visual Basic после ключевого слова Then обязательно должна идти команда, а так же слова Then и Else должны находиться на той же строке что и IF, иначе интерпретатор выдаст ошибку. Если для удобства восприятия необходимо Команду 1 перенести на новую строку, то необходимо воспользоваться символом «_» после Then.

If условие Then _
[Команда 1] _
[Else Команда 2]

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

If условие Then
[Команда 1]
[Команда 2]
.
[Else]
[Команда 3]
[Команда 4]
End If

Ключевое слово Else можно так же, как и в первом варианте не использовать, если нет необходимости.

И третий вариант конструкции, при котором происходит проверка условия, если первое условие не выполнено

If условие 1 Then
[Команда 1]
[Команда 2]
.
[ElseIf условие 2 Then
[Команда 3]
[Команда 4]
[Else
[Команда 5]
[Команда 6]
End If

В условиях также можно использовать логическое И (And), ИЛИ(Or) и отрицание НЕ (Not).
Рассмотрим несколько примеров использования выше перечисленных конструкций.

Пример 1

If a=b Then msgbox «а равняется b» Else msgbox «а не равно b»

Пример 2

В этом варианте Else не используем.
If a=b Then msgbox «а равняется b»

Пример 3

Используя «_» для интерпретатора Basic такая запись равносильна записи в Примере 1
If a=b Then _
msgbox «а равняется b» _
Else msgbox «а не равно b»

Пример 4
If a=b Then
msgbox «а равняется b»
a = a+b
Else
msgbox «а неравно b»
c = b
End If

Пример 5
If a=b Then
msgbox «а равняется b»
ElseIf a>b Then
msgbox «а больше b»
Else
msgbox «b больше a»
End If

«else without if» получает эту ошибку в excel vba

Я получаю ошибку «else without if» в коде ниже. Может кто-нибудь помочь?

2 Ответа

TL;DR: вам нужно переместить все после Then в новую строку.

В VBA однострочные- If — операторы имеют следующие характеристики:

  • У них нет End If , никогда .
  • Они должны быть написаны полностью , как одна строка. Один

Однако однострочный символ- if следует использовать исключительно для коротких утверждений. Как правило, не очень хорошая идея использовать его, когда у вас есть Else (не говоря уже о Else If ). Итак, в приведенном выше блоке кода второй и третий примеры не рекомендуются. Вместо этого вы должны написать свои If заявления следующим образом:

1 Вы можете, конечно, разбить операторы на несколько строк, используя _ , хотя. Смотрите это для получения дополнительной информации.

в логическое выражение, которое вы хотите использовать AND вместо &

кроме того, в таком запутанном случае блок Select Case гораздо более удобочитаем:

а вот еще один способ перевода того же самого If Then Else If вашего блока в Select Case :

Похожие вопросы:

Я не могу понять, почему VBA кричит на меня по этому поводу. Очень простой код, задействован только один оператор if, и он явно имеет Starting If и соответствующий конец If. Я являюсь разработчиком.

До сих пор никто solution не исправляет мою ошибку, какие-нибудь советы? Я отлаживаю макрос в VBA и получаю эту ошибку: Compile error: Else without If Любые советы о том, как это исправить? Вот.

Как вы обычно используете для замены if-without-else в Scala функциональным способом? Например, как этот типичный шаблон в императивном стиле: var list = List(a, b, c) if (flag) 0 ? days + ‘ day’ + (days > 1 ? ‘s’ : ») + ‘ ‘ : ») + hours+’:’+minutes+’:’+Math.round(seconds) Это моя.

У меня есть эта формула Excel ниже; DATE(LEFT(A1,3),MID(A1,6,1),MID(A1,7,1)) Я хотел бы преобразовать эту формулу Excel в пользовательскую функцию VBA. Public Function getDate(input_date As String).

Это мой первый проект vba, поэтому, пожалуйста, наберитесь терпения. Я создал форму пользователя Excel для добавления информации в базу данных. Когда я нажимаю add, у меня есть vba скрипт, который.

Я хочу написать формулу в excel. Я хочу реализовать ниже в excel if(C10 != SA) else else > > else .

Я запутался в том, как передать эту проблему с excel на VBA: В excel: Теоретик: =IF(cond1, IF(cond2, statement1,statement2),IF(cond2,statement3,statement4)) Фактические excel ячейки.

Else without if ошибка vba

“Next Without For” Compile Error is a very common compile-time error in Excel VBA. It implies that a Next statement must always have a preceding For statement that matches. If a Next statement is used without a corresponding For statement, this error is generated.

Let us look at some most common causes of the error and way to fix and avoid them.

Example 1: If statement without a corresponding “End If” statement

Every If statement (and If Else Statement) must have a corresponding End If statement along with it. As you can see in the above code, End If is missing after the Else block, causing the error. The right way to do it is

Example 2: Incorrect sequence of End If and Next statements

Here, the End If statement is not placed correctly causing overlapping as shown below:

For
If
Next
End If

The entire If statement (including, If, Else and End If statements), must be placed withing the For…Next block as shown below

Example 3: With statement has a corresponding End With Statement missing

Just like an If statement, the With statement should also have a corresponding End With statement, without which error will be thrown. The working example:

Example 4: Overlapping For and If Else statement

Say, in the example below, you want to do some processing only if a condition is false. Else you want to continue with the next counter of the For loop

Note: as in other programming languages, VBA does not have a continue option for a loop. When the control of the program reaches the first “Next counter” statement after the If statement — it finds that there is a Next statement within the If statement. However, there is no corresponding For statement within this If Block. Hence, the error.

So, you can use one of the two solutions below:

Simply remove the “next” statement after If

Not the if condition and place your code there. Else condition is not required at all

The bottom line is that the “If, Else, End If statement block” must be completely within the For loop.

Avoiding the Next without For error by using standard coding practices

The best way to avoid this error is to follow some standard practices while coding.

1. Code indentation: Indenting your code not only makes it more readable, but it helps you identify if a loop / if statement / with statement are not closed properly or if they are overlapping. Each of your If statements should align with an End If, each For statement with a Next, each With statement with an End With and each Select statement with an End Select

2. Use variable name with Next: Though the loop variable name is not needed with a next statement, it is a good practice to mention it with the Next statement.

This is particularly useful when you have a large number of nested for Loops.

3. As soon as you start a loop, write the corresponding end statement immediately. After that you can code the remaining statements within these two start and end statements (after increasing the indentation by one level).

If you follow these best practices, it is possible to completely and very easily avoid this error in most cases.

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

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

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

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

If. Then — Если То

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

Синтаксис

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

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

пример

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

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

X is Greater than Y

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

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

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

Синтаксис

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

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

пример

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

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

Y is Greater than X

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

if . elseif..else statement

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

Синтаксис

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

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

пример

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

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

X and Y are EQUAL

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

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

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

Синтаксис

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

пример

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

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

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.

пример

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

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

The Number is the Least Composite Number

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

VBA-Урок 7.1. Условия (Conditions)

Условия являются очень полезными при программировании, поскольку позволяют нам выполнять действия, в зависимости от установленных критериев (используется такой же принцип как и в IF функции Excel).

Наиболее важной функцией, которая задает условие является IF и сейчас мы посмотрим, как она работает:

Давайте перейдем к практике и вернемся к примеру, который мы использовали в уроке с переменными. Цель этой процедуры была в том, чтобы открыть диалоговое окно, которое бы содержало значение из строки, указанного в ячейке F5 :

Если вы введете букву в ячейку F5 , это повлечет ошибку. Мы хотим предотвратить это.

Давайте добавим условие, которое будет проверять — является ли введенное значение в ячейку F5 числом, перед тем, как код будет выполнен.

Мы воспользуемся функцией IsNumeric для проверки условия:

Нам также нужно прописать инструкции, если поставленное нами условие не выполнится:

Теперь нечисловое значения не повлечет никаких проблем.

Работая с нашим массивом, который содержит 16 строк данных, наш следующий шаг будет в проверке является ли переменная row_number: «больше чем или равно 2» и «меньше чем или равно 17».

Но сначала взглянем на операторы сравнения:

и эти полезные операторы:

Теперь давайте добавим одно из выше указанных условий AND между операторов сравнения:

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

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

В этом случае, мы используем функцию WorksheetFunction.CountA , которая является аналогом функции COUNTA в самом Excel.

Мы хотим, чтобы эта функция подсчитала количество непустых ячеек в первой колонке по записала полученное значение в переменную nb_rows:

ElseIf

ElseIf дает возможность добавлять дополнительные условия после IF команды:

Если УСЛОВИЕ 1 выполняется, Инструкция 1 будет выполнена и покинет оператор IF (который начинается с IF и заканчивается End If ). Если УСЛОВИЕ 2 принимает значение » ложь «, тогда будет выполнена Инструкция 2 , и если она в свою очередь возвращает » ложь «, тогда Инструкция 3 (под Else ) будет выполнена.

Далее есть пример с оценками от 1 до 6 в ячейке A1 и комментарием к этим оценкам в ячейке B1:

Select

Существует альтернатива использованию If со многими ElseIf инструкциями, а именно команда Select , которая больше подходит к такого рода ситуаций.

Рассмотрим пример макроса с оператором Select:

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

Источник

Adblock
detector

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.)

No, you didn’t:

If Cells(i, 3).Value = "BRITISH TELECOM" Or _
   Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
   Cells(i, 3).Value = "DTAG" Or _
   Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then

An alternative would be to use a Select Case statement. These are especially useful if you have many conditions to test:

Select Case Cells(i, 3).Value
    Case "BRITISH TELECOM", _
         "CHRISTIES INTERNATIO", _
         "DTAG", _
         "IMAGINE COMMUNICATIONS CORP"

        'Do something

    Case "Some other string", _
         "and another string"

        'Do something else

    Case Else

        'Do something if none of the other statements evaluated to True

End Select

That Select Case statement would be equivalent to the following If statement:

If Cells(i, 3).Value = "BRITISH TELECOM" Or _
   Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
   Cells(i, 3).Value = "DTAG" Or _
   Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then

        'Do something

ElseIf Cells(i, 3).Value = "Some other string" Or _
       Cells(i, 3).Value = "and another string" Then

        'Do something else

Else

        'Do something if none of the other statements evaluated to True

End If

Unrelated to the actual question, but in response to a further question in comments:

If you have error values in your data, they will not be able to be compared to Strings, so you will need to test for errors first.

For example:

If IsError(Cells(i, 3).Value) Then

    'Do whatever you want to do with error values such as #N/A

ElseIf Cells(i, 3).Value = "BRITISH TELECOM" Or _
   Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
   Cells(i, 3).Value = "DTAG" Or _
   Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then

    '...

or

If IsError(Cells(i, 3).Value) Then

    'Do whatever you want to do with error values such as #N/A

Else    

    Select Case Cells(i, 3).Value
        Case "BRITISH TELECOM", _
             "CHRISTIES INTERNATIO", _
             "DTAG", _
             "IMAGINE COMMUNICATIONS CORP"

            'Do something

        Case "Some other string", _
             "and another string"

            'Do something else

        Case Else

            'Do something if none of the other statements evaluated to True

    End Select

End If

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

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

Use OR with IF

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

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

Sub myMacro()

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

End Sub

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

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

Sub myMacro()

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

End Sub

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

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

Sub myMacro()

'three conditions to test using OR

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

End Sub

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

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

Sub myMacro()

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

    MsgBox "one of the conditions is true."

Else

    MsgBox "none of the conditions are true."

End If

End Sub

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

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

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

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

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

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

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

Syntax – IF Then Else

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

IF condition Then true_code [Else false_code]

Or

IF condition Then
true_code
Else
false_code
End IF

Note that the Else part of this statement is optional.

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

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

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

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

Hence you need to use the End IF statement.

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

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

Examples of Using IF Then Statement in VBA

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

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

Then you can use the following code:

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

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

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

If it’s less than 35, nothing happens.

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

The below code would do this:

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

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

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

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

Nested IF Then (Multiple IF Then statements)

So far we have used a single IF Then statement.

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

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

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

Multiple IF Then Statements

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

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

We can use the below code to get this done:

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

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

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

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

IF Then Else Statement

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

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

We can use the below code to get this done:

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

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

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

IF Then ElseIf Else Statement

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

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

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

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

Using AND and OR in IF Then Else

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

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

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

IF Condition1 AND Condition2 Then
true_code
Else
false_code
End IF

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

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

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

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

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

Here is the code that will do this:

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

The above code uses both OR and AND statements.

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

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

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

Using Not Equal to in If Then

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

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

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

Using If Then Else with Loops in VBA

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

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

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

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

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

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

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

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

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

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

Example 2 – Highlight Cells with Negative Values

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

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

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

Example 3 – Hide All the Worksheet Except the Current Worksheet

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

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

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

Example 4 – Extract the Numeric Part from an Alphanumeric String

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

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

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

If Then Else in VBA - Custom Function

Where to Put the VBA Code?

Wondering where the VBA code goes in your Excel workbook?

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

Here are the steps to do this:

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

You May Also Like the Following Excel Tutorials:

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

Like this post? Please share to your friends:
  • Vba excel if then else несколько условий
  • Vba excel if target address
  • Vba excel if sheet protected
  • Vba excel if row hidden
  • Vba excel if not isnumeric