EXPLANATION
This tutorial shows how to test if a range contains a specific value and return a specified value if the formula tests true or false, by using an Excel formula and VBA.
This tutorial provides one Excel method that can be applied to test if a range contains a specific value and return a specified value by using an Excel IF and COUNTIF functions. In this example, if the Excel COUNTIF function returns a value greater than 0, meaning the range has cells with a value of 500, the test is TRUE and the formula will return a «In Range» value. Alternatively, if the Excel COUNTIF function returns a value of of 0, meaning the range does not have cells with a value of 500, the test is FALSE and the formula will return a «Not in Range» value.
This tutorial provides one VBA method that can be applied to test if a range contains a specific value and return a specified value.
FORMULA
=IF(COUNTIF(range, value)>0, value_if_true, value_if_false)
ARGUMENTS
range: The range of cells you want to count from.
value: The value that is used to determine which of the cells should be counted, from a specified range, if the cells’ value is equal to this value.
value_if_true: Value to be returned if the range contains the specific value
value_if_false: Value to be returned if the range does not contains the specific value.
Содержание
- Premium Excel Course Now Available!
- Build Professional — Unbreakable — Forms in Excel
- 45 Tutorials — 5+ Hours — Downloadable Excel Files
- Excel VBA Check if a Cell is in a Range
- Sections:
- Check if Cell is in a Range Macro
- How to Use the Macro
- How Does the Macro Know if the Cell is in the Range?
- Check if Cell is in a Named Range
- Notes
- Question? Ask it in our Excel Forum
- Checking Values in Range Objects With VBA
- Print Values in Range One by One (Unformatted)
- Print Values in Range Row by Row (Formatted)
- Download Sample Workbook
- Проверка условий (If…Then…)
- Краткое руководство по VBA If Statement
- Что такое IF и зачем оно тебе?
- Тестовые данные
- Формат операторов VBA If Then
- Простой пример If Then
- Условия IF
- Использование If ElseIf
- Использование If Else
- Используя If And/If Or
- Функция IIF
- Использование Select Case
Premium Excel Course Now Available!
Build Professional — Unbreakable — Forms in Excel
45 Tutorials — 5+ Hours — Downloadable Excel Files
Excel VBA Check if a Cell is in a Range
BLACK FRIDAY SALE (65%-80% Off)
Excel Courses Online
Video Lessons Excel Guides
VBA that checks if a cell is in a range, named range, or any kind of range, in Excel.
Sections:
Check if Cell is in a Range Macro
How to Use the Macro
B3:D6 change this to the range that you want to check to see if the cell is within it.
Selection keep this the same to use the currently selected cell or range from the user or change it to a regular hard-coded range reference like Range(«A1») or whatever range you want.
‘Selection is NOT inside the range. under this line, put the code that you want to run when the cell is not within the range.
‘Selection IS inside the range. under this line, put the code that you want to run when the cell is within the range.
How Does the Macro Know if the Cell is in the Range?
Intersect(testRange, myRange) this checks if the range within the myRange variable overlaps or intersects with the range in the testRange variable. This function, the Intersect function, will return a range object where the two ranges overlap, or, if they don’t overlap, it will return nothing.
As such, we can use the IF statement to check if nothing was returned or not and we do that using Is Nothing after the Intersect function. The Is Nothing is what checks if the Intersect function returned nothing or not, which evaluates to TRUE or FALSE, which is then used by the IF statement to complete its logic and run.
This is how we get the full first line of the IF statement, and this is where all the magic happens:
If Intersect(testRange, myRange) Is Nothing Then
The rest of the IF statement is just a regular IF statement in VBA, with a section of code that runs if the cell is within the range and one that runs when the cell is outside of the range.
Check if Cell is in a Named Range
This is almost exactly the same as the previous macro except that we need to change the range reference from B3:D6 to the name of the named range; that’s it.
It could look like this:
For a more detailed expanation of how this macro works, look to the section above.
Notes
If the user makes a selection of multiple cells or a range, and any of those cells are within the test range, this macro will run the code for when the selection is inside the range.
Testing if a range is within a range simply uses the Intersect function in Excel VBA; however, due to how it works, it can seem confusing since we have to check if it Is Nothing or not. But, once you get used to writing this and seeing this in IF statements, it’s really not that difficult, just remember that, in this instance, you will want to pair the use of Intersect with Is Nothing and everything else should follow quite easily.
Download the sample file to get the macro in Excel.
Question? Ask it in our Excel Forum
Excel VBA Course — From Beginner to Expert
200+ Video Lessons 50+ Hours of Instruction 200+ Excel Guides
Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)
Источник
Checking Values in Range Objects With VBA
One thing I often found frustrating with VBA is the lack of any easy way to see the values in a range object.
I often use Debug.Print when debugging my VBA and I’d love to just be able to Debug.Print a range like you can with other variables.
But because a range is an object, not a variable, you can’t do that.
One way to see what’s in a range is to step through your code (pressing F8) and when the range is set, you can check the values in the range in the Locals window.
Our range looks like this
In the VBA editor go to the View menu and click on Locals Window.
Each time F8 is pressed one line of VBA is executed. When the range MyRange is set, you can see that values appear for it in the Locals window.
By examining the MyRange object you can drill down to see the values in it.
Your browser does not support the video tag.
You can also set a Watch on the MyRange object to examine it in the Watch window, but this is essentially doing the same thing as examining it in the Locals window.
Using both Locals and Watch windows require you to step though code and examine values as the code executes.
If you want to just let the VBA run and see the values in the range printed out to the Immediate window, you need to write some code to do this.
In the VBA editor press CTRL+G, or go to the View menu and click on Immediate Window.
Print Values in Range One by One (Unformatted)
The code shown below will go through each cell in the range and print its value to the Immediate window.
However because we are printing one value at a time, it doesn’t really give you a feel for the structure of the range. That is in this case, that there are 4 values per row/line.
Your browser does not support the video tag.
Print Values in Range Row by Row (Formatted)
This next sub stores each value in a row to an array, and then prints out all of these values using the JOIN function to create a string with values separated by a comma.
This formatted output gives a better representation of the actual structure of your range.
In this format, you can also use the output to write data to a CSV file.
Download Sample Workbook
Enter your email address below to download the workbook containing all the code from this post.
All the code in this post can be downloaded in this workbook.
Источник
Проверка условий (If…Then…)
Угадай, если сможешь, и выбери, если посмеешь
Краткое руководство по 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 «Пройдено» ElseIf score > 30 Then Debug.Print «Попробуй снова» Else Debug.Print «Ой» End If |
If без Endif (Только одна строка) |
If [условие верно] Then [действие] |
If value |
В следующем коде показан простой пример использования оператора VBA If
Что такое IF и зачем оно тебе?
Оператор VBA If используется, чтобы позволить вашему коду делать выбор, когда он выполняется.
Вам часто захочется сделать выбор на основе данных, которые читает ваш макрос.
Например, вы можете захотеть читать только тех учеников, у которых оценки выше 70. Когда вы читаете каждого учащегося, вы можете использовать инструкцию If для проверки отметок каждого учащегося.
Важным словом в последнем предложении является проверка. Оператор If используется для проверки значения, а затем для выполнения задачи на основе результатов этой проверки.
Тестовые данные
Мы собираемся использовать следующие тестовые данные для примеров кода в этом посте.
Формат операторов VBA If Then
Формат оператора If Then следующий
За ключевым словом If следуют условие и ключевое слово Then
Каждый раз, когда вы используете оператор 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 для отступа кода.
Если вы посмотрите на примеры кода на этом сайте, вы увидите, что код имеет отступ.
Простой пример If Then
Следующий код выводит имена всех студентов с баллами более 50.
- Василий Кочин
- Максим Бородин
- Дмитрий Маренин
- Олеся Клюева
- Евгений Яшин
Поэкспериментируйте с этим примером и проверьте значение или знак > и посмотрите, как изменились результаты.
Условия IF
Часть кода между ключевыми словами If и Then называется условием. Условие — это утверждение, которое оценивается как истинное или ложное. Они в основном используются с операторами Loops и If. При создании условия вы используете такие знаки, как «>, ,> =,
Условие | Это верно, когда |
x 5 | x больше, чем 5 |
x >= 5 | x больше, либо равен 5 |
x = 5 | x равен 5 |
x <> 5 | x не равен 5 |
x > 5 And 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) | Присваивание | Присвойте х значение, возвращаемое функцией |
Последняя запись в приведенной выше таблице показывает оператор с двумя равными. Первый знак равенства — это присвоение, а любые последующие знаки равенства — это условия.
Поначалу это может показаться странным, но подумайте об этом так. Любое утверждение, начинающееся с переменной и равно, имеет следующий формат
[переменная] [=] [оценить эту часть]
Поэтому все, что находится справа от знака равенства, оценивается и результат помещается в переменную. Посмотрите на последние три строки таблицы, как:
Использование If ElseIf
Инструкция ElseIf позволяет вам выбирать из нескольких вариантов. В следующем примере мы печатаем баллы, которые находятся в диапазоне.
Важно понимать, что порядок важен. Условие If проверяется первым.
Если это правда, то печатается «Высший балл», и оператор If заканчивается.
Если оно ложно, то код переходит к следующему ElseIf и проверяет его состояние.
Давайте поменяемся местами If и ElseIf из последнего примера. Код теперь выглядит так
В этом случае мы сначала проверяем значение более 75. Мы никогда не будем печатать «Высший балл», потому что, если значение больше 85, это вызовет первый оператор if.
Чтобы избежать подобных проблем, мы должны использовать два условия. Они помогают точно указать, что вы ищете, чтобы избежать путаницы. Пример ниже показывает, как их использовать. Мы рассмотрим более многочисленные условия в разделе ниже.
Давайте расширим оригинальный код. Вы можете использовать столько операторов ElseIf, сколько захотите. Мы добавим еще несколько, чтобы учесть все наши классификации баллов.
Использование If Else
Утверждение Else используется, как ловушка для всех. Это в основном означает «если бы не было условий» или «все остальное». В предыдущем примере кода мы не включили оператор печати для метки сбоя. Мы можем добавить это, используя Else.
Так что, если это не один из других типов, то это провал.
Давайте напишем некоторый код с помощью наших примеров данных и распечатаем студента и его классификацию.
Результаты выглядят так: в столбце E — классификация баллов
Используя If And/If Or
В выражении If может быть несколько условий. Ключевые слова VBA And и Or позволяют использовать несколько условий.
Эти слова работают так же, как вы используете их на английском языке.
Давайте снова посмотрим на наши примеры данных. Теперь мы хотим напечатать всех студентов, которые набрали от 50 до 80 баллов.
Мы используем Аnd, чтобы добавить дополнительное условие. Код гласит: если оценка больше или равна 50 и меньше 75, напечатайте имя студента.
Вывести имя и фамилию в результаты:
- Дмитрий Маренин
- Олеся Клюева
- Евгений Яшин
В нашем следующем примере мы хотим знать, кто из студентов сдавал историю или геометрию. Таким образом, в данном случае мы говорим, изучал ли студент «История» ИЛИ изучал ли он «Геометрия» (Ctrl+G).
- Василий Кочин
- Александр Грохотов
- Дмитрий Маренин
- Николай Куликов
- Олеся Клюева
- Наталия Теплых
- Дмитрий Андреев
Использование нескольких таких условий часто является источником ошибок. Эмпирическое правило, которое нужно помнить, должно быть максимально простым.
Использование IF AND
And работает следующим образом:
Условие 1 | Условие 2 | Результат |
ИСТИНА | ИСТИНА | ИСТИНА |
ИСТИНА | ЛОЖЬ | ЛОЖЬ |
ЛОЖЬ | ИСТИНА | ЛОЖЬ |
ЛОЖЬ | ЛОЖЬ | ЛОЖЬ |
Что вы заметите, так это то, что And верно только тогда, когда все условия выполняются.
Использование IF OR
Ключевое слово OR работает следующим образом
Условие 1 | Условие 2 | Результат |
ИСТИНА | ИСТИНА | ИСТИНА |
ИСТИНА | ЛОЖЬ | ИСТИНА |
ЛОЖЬ | ИСТИНА | ИСТИНА |
ЛОЖЬ | ЛОЖЬ | ЛОЖЬ |
Что вы заметите, так это то, что OR ложно, только когда все условия ложны.
Смешивание And и Or может затруднить чтение кода и привести к ошибкам. Использование скобок может сделать условия более понятными.
Использование IF NOT
Также есть оператор NOT. Он возвращает противоположный результат условия.
Условие | Результат |
ИСТИНА | ЛОЖЬ |
ЛОЖЬ | ИСТИНА |
Следующие две строки кода эквивалентны.
Помещение условия в круглые скобки облегчает чтение кода
Распространенное использование Not — при проверке, был ли установлен объект. Возьмите Worksheet для примера. Здесь мы объявляем рабочий лист.
Мы хотим проверить действительность mySheet перед его использованием. Мы можем проверить, если это Nothing.
Нет способа проверить, является ли это чем-то, поскольку есть много разных способов, которым это может быть что-то. Поэтому мы используем NOT с Nothing.
Если вы находите это немного запутанным, вы можете использовать круглые скобки, как здесь
Функция IIF
VBA имеет функцию, аналогичную функции Excel If. В Excel вы часто используете функцию If следующим образом:
= ЕСЛИ (F2 =»»,»», F1 / F2)
= If (условие, действие, если ИСТИНА, действие, если ЛОЖЬ).
VBA имеет функцию IIf, которая работает так же. Давайте посмотрим на примере. В следующем коде мы используем IIf для проверки значения переменной val. Если значение больше 10, мы печатаем ИСТИНА, в противном случае мы печатаем ЛОЖЬ.
В нашем следующем примере мы хотим распечатать «Удовлетворитеьно» или «Незачет» рядом с каждым студентом в зависимости от их баллов. В первом фрагменте кода мы будем использовать обычный оператор VBA If, чтобы сделать это.
В следующем фрагменте кода мы будем использовать функцию IIf. Код здесь намного аккуратнее.
Функция IIf очень полезна для простых случаев, когда вы имеете дело с двумя возможными вариантами.
Использование Nested IIf
Вы также можете вкладывать IIf-операторы, как в Excel. Это означает использование результата одного IIf с другим. Давайте добавим еще один тип результата в наши предыдущие примеры. Теперь мы хотим напечатать «Отлично», «Удовлетворительно» или «Незачетт» для каждого студента.
Используя обычный VBA, мы сделали бы это так
Используя вложенные IIfs, мы могли бы сделать это так
Использование вложенного IIf хорошо в простых случаях, подобных этому. Код прост для чтения и, следовательно, вряд ли вызовет ошибки.
Чего нужно остерегаться
Важно понимать, что функция IIf всегда оценивает как Истинную, так и Ложную части выражения независимо от условия.
В следующем примере мы хотим разделить по баллам, когда он не равен нулю. Если он равен нулю, мы хотим вернуть ноль.
Однако, когда отметки равны нулю, код выдаст ошибку «Делить на ноль». Это потому, что он оценивает как Истинные, так и Ложные утверждения. Здесь ложное утверждение, т.е. (60 / Marks), оценивается как ошибка, потому что отметки равны нулю.
Если мы используем нормальный оператор IF, он будет запускать только соответствующую строку.
Это также означает, что если у вас есть функции для ИСТИНА и ЛОЖЬ, то обе будут выполнены. Таким образом, IIF будет запускать обе функции, даже если он использует только одно возвращаемое значение. Например:
IF против IIf
В этом случае вы можете видеть, что IIf короче для написания и аккуратнее. Однако если условия усложняются, вам лучше использовать обычное выражение If. Недостатком IIf является то, что он недостаточно известен, поэтому другие пользователи могут не понимать его так же, как и код, написанный с помощью обычного оператора if.
Кроме того, как мы обсуждали в последнем разделе, IIF всегда оценивает части ИСТИНА и ЛОЖЬ, поэтому, если вы имеете дело с большим количеством данных, оператор IF будет быстрее.
Мое эмпирическое правило заключается в том, чтобы использовать IIf, когда он будет прост для чтения и не требует вызовов функций. Для более сложных случаев используйте обычный оператор If.
Использование Select Case
Оператор Select Case — это альтернативный способ написания статистики If с большим количеством ElseIf. Этот тип операторов вы найдете в большинстве популярных языков программирования, где он называется оператором Switch. Например, Java, C #, C ++ и Javascript имеют оператор switch.
Давайте возьмем наш пример DobClass сверху и перепишем его с помощью оператора Select Case.
Ниже приведен тот же код с использованием оператора Select Case. Главное, что вы заметите, это то, что мы используем “Case 85 to 100” rather than “marks >=85 And marks =85 And marks
Ответ на упражнение
Следующий код показывает, как выполнить вышеупомянутое упражнение.
Примечание: есть много способов выполнить задачу, поэтому не расстраивайтесь, если ваш код отличается.
Источник
-
#2
Hi and Welcome to the Board.
What specific value are you looking for in «C16»
AND
You want to copy range «F3» to «F last cell» to the first blank cell in «F» ?
-
#3
Hi Michael,
Thanks for the welcome. Basically I have created an invoice sheet (F3:P43) that uses lookups from standard formulas I use based on client, dates, etc, etc to calculate an invoice from other worksheets. What I was doing to keep track of invoices I’ve issued, is to copy and paste the issued invoice values below F43. I’ve ensured that the F column only contains the invoice numbers. So everything below row 43 contains copies of invoices.
I created a macro button to copy and paste values of F3:P43, starting from F44, to the next blank cell in column F. The invoices are always 40 rows long, and each cell in F contains the invoice number it corresponds to.
The reason I want to use VBA is to make sure that I don’t copy and paste duplicates unnecessarily.
-
#4
Ok, now I’m really confused……so what does «cell «C16» have to do with the copy and paste ?
-
#5
Sorry Michael,
I’m a bit tired.
«C16» is the cell/value I want to check/search against «F44:F1000»
IF — the value of «C16» is found in «F44:F100»
THEN — don’t copy and paste
ELSE — copy and paste
END IF
I’ve figured out my copy and paste code. What I’m stuck on, is trying to create a code that will search «F44:F1000» for a value in «C16».
-
#6
Maybe this
Code:
Sub CopyPaste()
Dim lr As Long
lr = Cells(Rows.Count, "F").End(xlUp).Row
For Each cell In Range("F3:F43")
If cell.Value = Range("C16").Value Then
MsgBox "Invoice number already issued."
Exit Sub
End If
Next cell
Range("F3:P43").Copy
Range("F" & lr + 1).PasteSpecial Paste:=xlPasteValues
End Sub
-
#7
Thanks Michael,
That worked great, the only thing I had to change was Line 4, «F3:F43» to «F44:F1000».
But is there away to replace «F44:F1000» I entered to some thing like «F44: («F» & lr + 1)»?
-
#8
MAybe
Code:
Sub CopyPaste()
Dim lr As Long
lr = Cells(Rows.Count, "F").End(xlUp).Row
For Each cell In Range("F44:F" & lr)
If cell.Value = Range("C16").Value Then
MsgBox "Invoice number already issued."
Exit Sub
End If
Next cell
'Range("F3:F43").Copy ' so should this line change too !!
Range("F44:F" & lr).copy ' to this ?
Range("F" & lr + 1).PasteSpecial Paste:=xlPasteValues
End Sub
-
#9
Perfect Michael, thanks a lot. It’s way too late on this side of the world, but I apprecciate all the help. Time for some sleep.
-
#10
OK, glad it worked. Thanks for the feedback
VBA that checks if a cell is in a range, named range, or any kind of range, in Excel.
Sections:
Check if Cell is in a Range Macro
Check if Cell is in a Named Range
Notes
Check if Cell is in a Range Macro
Sub CellinRange()
'######################################'
'######### TeachExcel.com #########'
'######################################'
'Tests if a Cell is within a specific range.
Dim testRange As Range
Dim myRange As Range
'Set the range
Set testRange = Range("B3:D6")
'Get the cell or range that the user selected
Set myRange = Selection
'Check if the selection is inside the range.
If Intersect(testRange, myRange) Is Nothing Then
'Selection is NOT inside the range.
MsgBox "Selection is outside the test range."
Else
'Selection IS inside the range.
MsgBox "Selection is inside the test range."
End If
End Sub
How to Use the Macro
B3:D6 change this to the range that you want to check to see if the cell is within it.
Selection keep this the same to use the currently selected cell or range from the user or change it to a regular hard-coded range reference like Range(«A1») or whatever range you want.
‘Selection is NOT inside the range. under this line, put the code that you want to run when the cell is not within the range.
‘Selection IS inside the range. under this line, put the code that you want to run when the cell is within the range.
How Does the Macro Know if the Cell is in the Range?
Intersect(testRange, myRange) this checks if the range within the myRange variable overlaps or intersects with the range in the testRange variable. This function, the Intersect function, will return a range object where the two ranges overlap, or, if they don’t overlap, it will return nothing.
As such, we can use the IF statement to check if nothing was returned or not and we do that using Is Nothing after the Intersect function. The Is Nothing is what checks if the Intersect function returned nothing or not, which evaluates to TRUE or FALSE, which is then used by the IF statement to complete its logic and run.
This is how we get the full first line of the IF statement, and this is where all the magic happens:
If Intersect(testRange, myRange) Is Nothing Then
The rest of the IF statement is just a regular IF statement in VBA, with a section of code that runs if the cell is within the range and one that runs when the cell is outside of the range.
Check if Cell is in a Named Range
This is almost exactly the same as the previous macro except that we need to change the range reference from B3:D6 to the name of the named range; that’s it.
It could look like this:
Sub CellinRange()
'######################################'
'######### TeachExcel.com #########'
'######################################'
'Tests if a Cell is within a specific range.
Dim testRange As Range
Dim myRange As Range
'Set the range
Set testRange = Range("MyNamedRange")
'Get the cell or range that the user selected
Set myRange = Selection
'Check if the selection is inside the range.
If Intersect(testRange, myRange) Is Nothing Then
'Selection is NOT inside the range.
MsgBox "Selection is outside the test range."
Else
'Selection IS inside the range.
MsgBox "Selection is inside the test range."
End If
End Sub
For a more detailed expanation of how this macro works, look to the section above.
Notes
If the user makes a selection of multiple cells or a range, and any of those cells are within the test range, this macro will run the code for when the selection is inside the range.
Testing if a range is within a range simply uses the Intersect function in Excel VBA; however, due to how it works, it can seem confusing since we have to check if it Is Nothing or not. But, once you get used to writing this and seeing this in IF statements, it’s really not that difficult, just remember that, in this instance, you will want to pair the use of Intersect with Is Nothing and everything else should follow quite easily.
Download the sample file to get the macro in Excel.
Similar Content on TeachExcel
Excel Data Validation — Limit What a User Can Enter into a Cell
Tutorial:
Data Validation is a tool in Excel that you can use to limit what a user can enter into a…
Logical Operators in Excel VBA Macros
Tutorial: Logical operators in VBA allow you to make decisions when certain conditions are met.
They…
Make a UserForm in Excel
Tutorial: Let’s create a working UserForm in Excel.
This is a step-by-step tutorial that shows you e…
Sum Values that Equal 1 of Many Conditions across Multiple Columns in Excel
Tutorial:
How to Sum values using an OR condition across multiple columns, including using OR with …
VBA Comparison Operators
Tutorial: VBA comparison operators are used to compare values in VBA and Macros for Excel.
List of V…
Subscribe for Weekly Tutorials
BONUS: subscribe now to download our Top Tutorials Ebook!
Many times as a developer you might need to find a match to a particular value in a range or sheet, and this is often done using a loop. However, VBA provides a much more efficient way of accomplishing this using the Find method. In this article we’ll have a look at how to use the Range.Find Method in your VBA code. Here is the syntax of the method:
expression.Find (What , After , LookIn , LookAt , SearchOrder , SearchDirection , MatchCase , MatchByte , SearchFormat )
where:
What: The data to search for. It can be a string or any of the Microsoft Excel data types (the only required parameter, rest are all optional)
After: The cell after which you want the search to begin. It is a single cell which is excluded from search. Default value is the upper-left corner of the range specified.
LookIn: Look in formulas, values or notes using constants xlFormulas, xlValues, or xlNotes respectively.
LookAt: Look at a whole value of a cell or part of it (xlWhole or xlPart)
SearchOrder: Search can be by rows or columns (xlByRows or xlByColumns)
SearchDirection: Direction of search (xlNext, xlPrevious)
MatchCase: Case sensitive or the default insensitive (True or False)
MatchByte: Used only for double byte languages (True or False)
SearchFormat: Search by format (True or False)
All these parameters correspond to the find dialog box options in Excel.
Return Value: A Range object that represents the first cell where the data was found. (Nothing if match is not found).
Let us look at some examples on how to implement this. In all the examples below, we will be using the table below to perform the search on.
Example 1: A basic search
In this example, we will look for a value in the name column.
Dim foundRng As Range Set foundRng = Range("D3:D19").Find("Andrea") MsgBox foundRng.AddressThe rest of the parameters are optional. If you don’t use them then Find will use the existing settings. We’ll see more about this shortly.
The output of this code will be the first occurrence of the search string in the specified range.
If the search item is not found then Find returns an object set to Nothing. And an error will be thrown if you try to perform any operation on this (on foundRng in the above example)
So, it is always advisable to check whether the value is found before performing any further operations.
Dim foundRng As Range Set foundRng = Range("D3:D19").Find("Andrea") If foundRng Is Nothing Then MsgBox "Value not found" Else MsgBox foundRng.Address End IfLet us know have a look at the optional parameters. To keep it simple, we will exclude the above error handling in the subsequent examples.
Example 2: Using after
Set foundRng = Range("D3:D19").Find("Andrea", Range("D6"&amp;amp;amp;amp;amp;amp;lt;span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"&amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;lt;/span&amp;amp;amp;amp;amp;amp;gt;)) MsgBox foundRng.AddressOR
Set foundRng = Range("D3:D19").Find("Andrea", After:=Range("D6")) MsgBox foundRng.AddressThe highlighted cell will be searched for
Example 3: Using LookIn
Before seeing an example, here are few things to note with LookIn
- Text is considered as a value as well as a formula
- xlNotes is same as xlComments
- Once you set the value of LookIn all subsequent searches will use this setting of LookIn (using VBA or Excel)
'Look in values Set foundRng = Range("A3:H19").Find("F4", , xlValues) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $B$4 'Look in values and formula Set foundRng = Range("A3:H19").Find("F4", LookIn:=xlFormulas) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $B$4 'Look in values and formula (as previous setting is preserved) Set foundRng = Range("H3:H19").Find("F4") MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $H$4 'Look in comments Set foundRng = Range("A3:H19").Find("F4", , xlNotes) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $D$4Example 4: Using LookAt
'Match only a part of a cell Set foundRng = Range("A3:H19").Find("John", , xlValues, xlPart) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $D$8 'Match entire cell contents Set foundRng = Range("A3:H19").Find("John", LookAt:=xlWhole) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $D$9LookAt setting too is preserved for subsequent searches.
Example 5: Using SearchOrder
'Searches by rows Set foundRng = Range("A3:H19").Find("Sa", , , xlPart, xlRows) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $G$4 'Searches by columns Set foundRng = Range("A3:H19").Find("Sa", SearchOrder:=xlColumns) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $F$5SearchOrder setting is preserved for subsequent searches.
Example 6: Using SearchDirection
'Searches from the bottom Set foundRng = Range("A3:H19").Find("Alexander", , , , , xlPrevious) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $D$18 'Searches from the top Set foundRng = Range("A3:H19").Find("Alexander", SearchDirection:=xlNext) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $D$11Example 7: Using MatchCase
'Match Case Set foundRng = Range("A3:H19").Find("Sa", , , , xlRows, , True) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $F$5 'Ignore case Set foundRng = Range("A3:H19").Find("Sa", MatchCase:=False) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $G$4Example 8: Using SearchFormat
When you search for a format it is important to note that the format settings stick until you change them. So, before you use SearchFormat, it is a good practice to always clear any previous formats that have been set.
'Clear any previous format set Application.FindFormat.Clear 'Set the format for find operation Application.FindFormat.Interior.Color = 14348258 'Match format Set foundRng = Range("A3:H19").Find("SA", MatchCase:=True, SearchFormat:=True) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $G$15 'Search without matching the format Set foundRng = Range("A3:H19").Find("SA", MatchCase:=True, SearchFormat:=False) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $G$4 'Search only for cells of a particular format Set foundRng = Range("B3:H19").Find("*", MatchCase:=True, SearchFormat:=True) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $B$3Example 9: FindNext and FindPrevious
In all the previous examples, we have been looking for just the first occurrence of the search criteria. If you want to find multiple occurrences, we use the FindNext and FindPrevious methods. Both of these need a reference to the last cell found, so that the search continues after that cell. If this argument is dropped, it will keep returning the first occurrence.
'First occurrence Set foundRng = Range("A3:H19").Find("Ms") MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $C$5 'Find the next occurrence Set foundRng = Range("A3:H19").FindNext(foundRng) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $C$10 'Find the previous occurrence again Set foundRng = Range("A3:H19").FindPrevious(foundRng) MsgBox foundRng.Address 'Output --&amp;amp;amp;amp;amp;amp;gt; $C$5If you are looking to find or list all files and directories in a folder / sub-folder, you can refer to the articles below:
Find and List all Files and Folders in a Directory
Excel VBA, Find and List All Files in a Directory and its Subdirectories
For using other methods in addition to Find, please see:
Check if Cell Contains Values in Excel
The IF…THEN statement is one of the most commonly used and most useful statements in VBA. The IF…THEN statement allows you to build logical thinking inside your macro.
The IF…THEN statement is like the IF function in Excel. You give the IF a condition to test, such as “Is the customer a “preferred” customer?” If the customer is classified as “preferred” then calculate a discount amount. Another test could be to test the value of a cell, such as “Is the cell value greater than 100?” If so, display the message “Great sale!” Otherwise, display the message “Better luck next time.”
The IF…THEN can also evaluate many conditions. Like the AND function, you can ask several questions and all the questions must evaluate to TRUE to perform the action. Similarly, you can ask several questions and if any single or multiple of questions are true, the action will be performed. This is like an OR function in Excel.
Task #1 – Simple IF
In this example we will evaluate a single cell. Once we have the logic correct, we will apply the logic to a range of cells using a looping structure.
In Excel, open the VBA Editor by pressing F-11 (or press the Visual Basic button on the Developer ribbon.)
Right-click “This Workbook” in the Project Explorer (upper-left of VBA Editor) and select Insert ⇒ Module.
In the Code window (right panel) type the following and press ENTER.
Sub Simple_If()
We want to evaluate the contents of cell B9 to determine if the value is greater than 0 (zero). If the value is >0, we will display the value of cell B9 in cell C9.
In the Code window, click between the Sub and End Sub commands and enter the following.
If Range("B9").Value > 0 Then Range("C9").Value = Range("B9").Value
If you only have a single action to perform, you can leave all the code on a single line and you do not have to close the statement with an END IF.
If you have more than one action to perform, you will want to break your code into multiple lines like the following example.
When using this line-break style, don’t forget to include the END IF statement at the end of the logic.
Test the function by executing the macro. Click in the code and press F5 or click the Run button on the toolbar at the top of the VBA Editor window.
The number 45 should appear in cell C9.
If we change the value in cell B9 to -2, clear the contents of cell C9 and re-run the macro, cell C9 will remain blank.
Suppose we want to test the values in Column B to see if they are between 1 and 400. We will use an AND statement to allow the IF to perform multiple tests.
Update the code with the following IF statement.
Sub Simple_If()
If Range("B9").Value > 0 And Range("B9").Value <= 400 Then
Range("C9").Value = Range("B9").Value
End If
End Sub
Test the macro by changing the value in cell B9 to values between 1 and 400 as well as testing values >400 or <=0 (remember to clear the contents of cell C9 prior to each test).
Task #2 – Color all values between 1 and 400 green (Looping Through Data)
Now we want to loop through the values in Column B and perform the test on each value.
Below the existing procedure, start a new procedure named IF_Loop(). Type the following and press ENTER.
Sub IF_Loop()
We want to color all the cells in range B9:B18 green if their cell value is between 1 and 400.
There are many ways to determine the data’s range. For examples of several range detection/selection techniques, click the link below to check out the VBA & Macros course.
Unlock Excel VBA and Excel Macros
The technique we will use is to convert the plain table to a Data Table and use Table References. Table References are great because they automatically expand and contract when data is either added or removed from the table. This keep you from having to update all your formulas and VBA code when data ranges change, which they often do.
Click anywhere in the table and press CTRL-T and then click OK.
We want to restore our original cell colors. Select Table Tools ⇒ Design ⇒ Table Styles (group) ⇒ Expand the table styles list and select Clear (bottom of list).
Rename the table (upper-left) to “TableSales”.
Select cell D7 (or any blank cell) and type an equal’s sign.
=
Select cells B9:B18 and note the update to the formula. This contains the proper method for referring to table fields (columns).
=TableSales[Sales]
Highlight the reference in the formula bar (do not include the equal’s sign) and press CTRL-C to copy the reference into memory.
Press ESC to abandon the formula.
Return to the VBA Editor and click between the Sub and End Sub commands in the IF_Loop() procedure.
We want to loop through the sales column of the table. For detailed information on creating and managing looping structures, click the link below.
Excel VBA: Loop through cells inside the used range (For Each Collection Loop)
We want the cell color to change to green if the cell’s value is between 1 and 400. We can use the Interior object to set the Color property to green. Enter the following code in the VBA Editor.
Sub IF_Loop()
Dim cell As Range
For Each cell In Range("TableSales[Sales]")
If cell.Value > 0 And cell.Value <= 400 Then
cell.Interior.Color = VBA.ColorConstants.vbGreen
End If
Next cell
End Sub
Run the updated code to see the results as witnessed below.
The color green is a bit on the bright side. We want a pale green, but we don’t know the color code for pale green. Here is a great way to discover the color of any cell.
Open the Immediate Windows by pressing CTRL-G or clicking View à Immediate Window from the VBA Editor toolbar. This should present the Immediate Window in the lower portion of the VBA Editor.
Select an empty cell and set the fill color to a pale green.
With the newly colored cell selected, click in the Immediate Window of the VBA Editor and enter the following text and press ENTER.
? activecell.Interior.Color
The above command will return the value of the active cell’s fill color. In this case, pale green is 9359529.
Update the VBA code to use the color code for pale green instead of the VBA green.
cell.Interior.Color = 9359529
Run the updated code and notice the colors are a more pleasant pale green.
Task #3 – Color all cells that are <=0 and >400 yellow
Now that we have identified all the numbers between 1 and 400, let’s color the remaining cells yellow. The color code for the yellow we will be using is 6740479.
To add the second possible action will require the addition of an ELSE statement at the end of our existing IF statement. Update the code with the following modification.
Else
cell.Interior.Color = 6740479
Run the updated code and notice how all the previously white cells are now yellow.
Task #4 – Negative values will be colored red
We will now update the code to color all the negative valued cells red. The color code for the red we will be using is 192.
To add the third possible action will require the addition of an ELSEIF statement directly after the initial IF statement. Update the code with the following modification.
ElseIf cell.Value < 0 Then
cell.Interior.Color = 192
Run the updated macro and observe that all the negative valued cells are now filled with the color red.
Feel free to Download the Workbook HERE.
Published on: August 23, 2018
Last modified: February 21, 2023
Leila Gharani
I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.
My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.
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
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”
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
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
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
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
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
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!
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
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
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 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
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 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
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
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
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:
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.
If you want to be an advanced VBA user then an IF statement is a must-learn. And, I believe that you are already familiar with the word IF and you are frequently using it as a worksheet function.
In VBA, IF works just like the same. Its basic idea is to perform a task when a condition is TRUE else do nothing or do something else. You can write simply as well as in complex conditions.
For understanding purposes, I have split it into three different parts.
- A condition to test.
- A task to perform if the condition is TRUE.
- A task to perform if the condition is FALSE.
This is what it looks like in real life:
In the above example, rain is a condition. If this condition is TRUE, the boy will open his umbrella and if the condition is FALSE he will wear his hat. Conditions are everywhere in our day-to-day life. But now, let’s back to our coding world and explore it.
Syntax: VBA IF
We have three different types of IF statements in VBA.
1. IF-Then
IF THEN is the simplest form of an IF statement. All we need to do is specify a condition to check and if that condition is TRUE it will perform a task. But, if that condition is FALSE it will do nothing and skip the line instantly.
Syntax
IF condition Then statement[s]
In the above syntax, we have to specify a condition to evaluate and a task to perform if that condition is TRUE.
Example
In the above example, we have used verified that cell A1 has value 10 in it and if it has, the statement will show a message box with the message “Cell A1 has value 10”.
Sub CheckValue()
If Range("A1").Value = 10 Then
MsgBox ("Cell A1 has value 10")
End Sub
2. IF-Then-Else
You can use the IF-Then-Else statement where you want to perform a specific task if a condition is TRUE and a different task if a condition is FALSE.
Syntax
IF Condition Then
Statement[s]
Else
Statement[s]
End If
With the above syntax, we can perform different tasks according to the result of a condition. If the condition is TRUE then it will perform the statement which you have mentioned after “Then” or if the condition is FALSE it will perform the statement which you have mentioned after “Else”.
Example
Sub CheckValue()
If Range("A1").Value = "10" Then
MsgBox ("Cell A1 has value 10")
Else
MsgBox ("Cell A1 has a value other than 10")
End Sub
In the above example, I have used the IF-Then-Else statement to check the value in cell A1.
If cell A1 has a value of 10, you will get a message box showing “Cell A1 has a value of 10” and if there is any other value in cell A1 you get a message box showing “Cell A1 has a value other than 10”. So, here we are able to perform different tasks according to the result of the condition.
3. IF-Then-Elseif-Else
This is the most useful and important type of IF which will help you to write advanced condition statements. In this type, you can specify the second condition after evaluating your first condition.
Syntax
IF Condition Then
Statement[s]
Elseif Condition Then
Statement[s]
Else
Statement[s]
End If
In the above syntax, we have:
- A condition to evaluate.
- A statement to perform if that condition is TURE.
- If that condition is FALSE then we have the second condition to evaluate.
- And, if the second condition is TRUE we have a statement to perform.
- But, if both conditions, first and second are FALSE then it will perform a statement that you have mentioned after “Else”.
And, the best part is you can use any number of “Elseif” in your code. That means you can specify any number of conditions in your statement.
Example
Sub check_grade()
If Range("A2").Value = "A" Then
MsgBox "Very Good"
Else
If Range("A2").Value = "B" Then
MsgBox "Good"
ElseIf Range("A2").Value = "C" Then
MsgBox "Average"
ElseIf Range("A2").Value = "D" Then
MsgBox "Poor"
ElseIf Range("A2").Value = "E" Then
MsgBox "Very Poor"
Else
MsgBox "Enter Correct Grade"
End Sub
In the above example, we have written a macro that will first check cell A2 for the value “A” and if the cell has the grade “A”, the statement will return the message “Very Good”.
This statement will first check cell A2 for value “A” and if the cell has the grade “A”, the statement will return the message “Very Good”.
And, if the first condition is FALSE then it will evaluate the second condition and return the message “Good” if the cell has a grade of “B”.
And, if the second condition is false then it will go to the third condition and so on. In the end, if all five conditions are false it will run the code which I have written after else.
The secret about writing an IF statement in VBA
Now, you know about all the types of IF and you are also able to choose one of them according to the task you need to perform. Let me tell you a secret.
One Line IF statement Vs. Block IF statement
You can write an IF statement in two different ways and both have advantages and disadvantages. Have a look.
1. One Line Statement
The one-line statement is perfect if you are using the IF-Then statement. The basic to use one line statement is to write your entire code in one line.
If A1 = 10 Then Msgbox("Cell A1 has value 10")
In the above statement, we have written an IF statement to evaluate if cell A1 has a value of 10 then it will show a message box. The best practice to use one line statement is when you have to write a simple code. Using one-line code for complex and lengthy statements is hard to understand.
[icon name=”lightbulb-o” unprefixed_] Quick Tip: While writing single-line code you don’t need to use Endif to end the statement.
2. Block Statement
A Block statement is perfect when you want to write your code in a decent and understandable way. When you writing a block statement you can use multiple lines in your macro which give you a neat and clean code.
Sub check_value()
If Range(“A1”).Value = “10” Then
MsgBox ("Cell A1 has value 10")
Else
MsgBox ("Cell A1 has a value other than 10")
End If
End Sub
In the above example, we have written an IF-Then-Else statement in blocks. And, you can see that it is easy to read and even easy to debug.
When you will write complex statements (which you will definitely do after reading this guide) using block statements are always good. And, while writing nested If statements you can also add indentation in your line for more clarity.
[icon name=”lightbulb-o” unprefixed_] Quick Tip – You have an exception that you can skip using Else at the end of your code when you are using IF-Then-Elseif-Else. This is very helpful when you do not need to perform any task when none of the conditions is TRUE in your statement.
8 Real Life Examples
Here I have listed some simple but useful examples which you can follow along.
1. Nested IF
The best part of the IF statement is you create nesting statements. You can add a second condition in the first condition.
Sub NestIF()
Dim res As Long
res = MsgBox("Do you want to save this file?", vbYesNo, "Save File")
If res = vbYes Then 'start of first IF statement
If ActiveWorkbook.Saved <> True Then 'start of second IF statement.
ActiveWorkbook.SaveMsgBox ("Workbook Saved")
Else
MsgBox "This workbook is already saved"
End If 'end of second IF statement
Else
MsgBox "Make Sure to save it later"
End If ' end of first IF statement
End Sub
In the above example, we have used a nested IF statement. When you run this macro you will get a message box with the OK and Cancel options. Work of conditional statement starts after that.
First, it will evaluate which button you have clicked. If you clicked “Yes” then nest it will evaluate whether your worksheet is saved or not.
If your workbook is not saved, it will save it and you will get a message. And, if the workbook is already saved it will show a message about that.
But, If you click on the button the condition of the first macro will be FALSE and you will only get a message to save your book later.
The basic idea in this code is that the second condition is totally dependent on the first condition if the first condition is FALSE then the second condition will not get evaluated.
More on Nested IF
2. Create Loop With IF and GoTo
You can also create a loop by using goto with IF. Most programmers avoid writing loops this way as we have better ways for a loop. But there is no harm to learn how we can do this.
Sub auto_open()
Alert: If InputBox("Enter Username") <> "Puneet" Then
GoTo Alert
Else
MsgBox "Welcome"
End If
End Sub
In the above example, we have used a condition statement to create a loop. We have used auto_open as the name of the macro so that whenever anyone opens the file it will run that macro.
The user needs to enter a username and if that username is not equal to “Puneet” it will repeat the code and show the input box again. And, if you enter the right text then he/she will be able to access the file.
3. Check if a Cell Contains a Number
Here we have used a condition to check whether the active cell contains a numeric value or not.
Sub check_number()
If IsNumeric(Range("B2").Value) Then
MsgBox "Yes, active cell has a number."
Else
MsgBox "No, active cell hasn't a number."
End If
End Sub
In the above example, I have written a condition by using the isnumeric function in VBA which is the same as the worksheet’s number function to check whether the value in a cell is a number or not.
If the value is a number it will return TRUE and you will get a message “Yes, Active Cell Has A Numeric Value”. And, if the value is non-number then you will get a message “No Numeric Value In Active Cell”.
4. Using OR and AND With IF
By using IF OR you can specify two or more conditions and perform a task if at least one condition is TRUE from all.
Sub UsingOR()
If Range("A1") < 70 Or Range("B1") < 70 Then
MsgBox "You Are Pass"
Else
If Range("A1") < 40 And Range("B1") < 40 Then
MsgBox "You Are Pass"
Else
MsgBox "You Are Fail"
End If
End If
End Sub
In the above example, in line 2, we have two conditions using the OR. If a student gets 70 marks in any of the subjects the result will be a “Pass”. And on line 7, we have two conditions using the AND operator. If a student gets more than 40 marks in both of the subjects the result will be “Pass”.
By using the IF AND you can specify more than one condition and perform a task if all the conditions are TRUE.
5. Using Not With IF
By using NOT in a condition you can change TRUE into FALSE and FALSE into TRUE.
VBA IF Not
Sub IF_Not()
If Range(“D1”) <= 40 And Not Range(“E1”) = “E” Then
MsgBox "You Are Pass."
Else
MsgBox "You Are Fail."
End If
End Sub
In the above example, we have used NOT in the condition. We have two cell with the subject score. In one cell score is in numbers and in another cell it has grades.
- If a student has marks above 40 in the first subject and above E grade in the second subject then he/she is a PASS.
- If a student has marks above 40 in the first subject and above E grade in the second subject then he/she is PASS.
So every time when a student’s marks are more than 40 and a grade other than E we will get a message “You are Pass” or else “You are Fail”.
6. IF Statement With a Checkbox
Now, here we are using a checkbox to run a macro.
Sub ship_as_bill()
If Range("D15") = True Then
Range("D17:D21") = Range("C17:C21")
Else
If Range(“D15”) = False Then
Range("D17:D21").ClearContents
Else
MsgBox (“Error!”)
End If
End If
End Sub
In the above example, we have used an IF statement to create a condition that if the checkbox is tick marked then range D17:D21 is equal to range C17:C21. And, if the checkbox is not ticked then range D17:D21 will be blank.
Using this technique we can use the billing address as the shipping address and if we need something else we can enter the address manually.
7. Check if a Cell is Merged
And here, we are writing a condition to get an alert if active cell is merged.
Sub MergeCellCheck()
If ActiveCell.MergeCells Then
MsgBox "Active Cell Is Merged"
Else
MsgBox "Active Cell Is Not Merged"
End If
End Sub
In the above code, we have used merge cells to check whether the active cell is merged or not. If the active cell is merged then the condition will return an alert for that.
8. Delete the Entire Row if a Cell is Blank
Here we are using IF to check whether a row is blank or not. And, if that row is blank statement will delete that particular row.
Sub DeleteRow()
If Application.CountA(ActiveCell.EntireRow) = 0 Then
ActiveCell.EntireRow.Delete
Else
MsgBox Application.CountA(ActiveCell.EntireRow) & "Cell(s) have values in this row"
End If
End Sub
In the above example, it will first check for the cells which have value in them. If the count of cells with a value is zero then the condition will delete the active row else return the alert showing the number of cells having value.
Conclusion
As I said it’s one of the most important parts of VBA and must learn if you want to master VBA. With the IF statement, you can write simple codes as well as complex codes. You can also use logical operators and write nested conditions.
I hope this guide will help you to write better codes.
Now tell me this. Do you write conditions in VBA frequently? What kind of codes do you write? Please share your views with me in the comment section. And, please don’t forget to share this guide with your friends.
Related: Exit IF