Напишите код, который делает то, что он говорит, и говорит, что он делает.
For Each ws In ThisWorkbook.Sheets
If ws.Name = "Navy Reqs" Then
ws.Select
nReqs = get_num_rows
Cells(1, 1).Select
If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
Selection.AutoFilter
Else If ws.Name <> "temp" Then
ws.Select
nShips = get_num_rows
End If
Next
Это все, что вам нужно. Инструкция, которая означает «здесь какой-то бесполезный код», не существует в VBA.
Вы хотите, чтобы комментарии, которые говорят, почему, а не то, что комментарий, который говорит: 'do nothing
— это полная противоположность этому. Не пишите no-op код, это чистый шум.
Предполагая, что Python- pass
работает как оператор С# continue
и переходит к следующей итерации, эквивалент VBA является единственным и единственным законным использованием перехода GoTo
:
For ...
If ... Then GoTo Skip
...
Skip:
Next
Есть ли в VBA эквивалент Python «pass», чтобы просто ничего не делать в коде?
например:
For Each ws In ThisWorkbook.Sheets
If ws.Name = "Navy Reqs" Then
ws.Select
nReqs = get_num_rows
Cells(1, 1).Select
If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
Selection.AutoFilter
ElseIf ws.Name = "temp" Then
pass
Else
ws.Select
nShips = get_num_rows
End If
Next
Я получаю ошибку здесь, что проход не определен. Благодарю.
2017-10-17 17:11
5
ответов
Решение
Просто удали pass
и снова запустите код. VBA будет рад принять то, что я верю
2017-10-17 17:18
Не включайте никаких заявлений:
Sub qwerty()
If 1 = 3 Then
Else
MsgBox "1 does not equal 3"
End If
End Sub
2017-10-17 17:19
Напишите код, который делает то, что говорит, и говорит, что он делает.
For Each ws In ThisWorkbook.Sheets
If ws.Name = "Navy Reqs" Then
ws.Select
nReqs = get_num_rows
Cells(1, 1).Select
If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
Selection.AutoFilter
Else If ws.Name <> "temp" Then
ws.Select
nShips = get_num_rows
End If
Next
Это все, что вам нужно. Инструкция, которая означает «вот какой-то бесполезный код», не существует в VBA.
Вы хотите комментарии, которые говорят почему, а не что — комментарий, который говорит 'do nothing
полная противоположность этому. Не пишите неоперативный код, это чистый шум.
Предполагая Python pass
работает как C# continue
оператора и переходит к следующей итерации, тогда VBA-эквивалент — это единственное законное использование GoTo
Прыгать:
For ...
If ... Then GoTo Skip
...
Skip:
Next
2017-10-17 17:30
Просто оставьте это пустым. Вы также можете использовать оператор Select, его легче читать.
For Each ws In ThisWorkbook.Sheets
Select Case ws.Name
Case "Navy Reqs":
'...
Case "temp":
'do nothing
Case Else:
'...
End Select
Next
2017-10-17 17:18
Этот код показывает тест IF, который продолжает поиск, пока не получит совпадение.
Function EXCAT(Desc)
Dim txt() As String
' Split the string at the space characters.
txt() = Split(Desc)
For i = 0 To UBound(txt)
EXCAT = Application.VLookup(txt(i), Worksheets("Sheet1").Range("Dept"), 2, False)
If IsError(EXCAT) Then Else Exit Function
Next
' watch this space for composite word seach
EXCAT = "- - tba - -"
End Function
2018-10-14 00:29
Я кодировал на COBOL много лет, и эквивалентное выражение «ничего не делать» звучит так: NEXT SENTENCE
.
В VBA я создаю фиктивную переменную (иногда глобальную) dim dummy as integer
а затем, когда мне нужно действие «ничего не делать» в If..Then..Else
Я ввел строку кода: dummy = 0
.
2019-06-19 15:44
На самом деле это законный вопрос. Я хочу запустить процедуру отладки, которая останавливается при достижении определенного критического значения, скажем, 8, т. Е. Устанавливает точку останова на x = 8, а затем поэтапно. Так что полезна следующая конструкция:
Select Case x
Case 21
'do nothing
Case 8
'do nothing
Case 14
'do nothing
Case 9
'do nothing
End Select
- Поскольку вы не можете поставить точку останова на комментарии, необходимо собственное выражение.
- Вы также не можете поставить точку останова на операторах Case, потому что они выполняются каждый раз.
Очевидно, здесь все в порядке, например, x=x
, но было бы неплохо иметь что-нибудь формальное, например pass
.
Но я использовал x=x
.
2020-04-02 20:34
В большинстве языков есть «пустой» или «пустой» оператор, как в Python
pass
. Эти утверждения эволюционировали, потому что они практически полезны, а в некоторых грамматиках необходимы. Например, как предлагали другие, пустые операторы могут служить в качестве якорей без побочных эффектов для отладчика.
Я использую:
Debug.Assert True
Обратите внимание, что если ваш вариант использования — установить условную точку останова, вы можете найти
Stop
более полезно, например:
If targetShape.Type = msoAutoShape Then
Stop
End
2020-09-14 10:04
If/Else Then Do Nothing in Excel VBA
When we don’t want to do anything in an If-then-else statement, believe it or not, we can simply not place any code!
This is the most straightforward way to ‘do nothing’ in VBA. VBA does not have a specific statement that can be used for ‘doing nothing’. Unlike Python, which has a pass statement that can be placed where we do not want to take any action, VBA does not use such a statement.
A slightly more complex solution is needed if by trying to do ‘nothing’ we are actually trying to skip an iteration in a loop.
Example 1: No Code
In this example, we simply do not place any code in the location where we do not want anything to happen. We choose to not do anything if the statement is true, but if the statement is false, then it will print “something will happen because the statement is false.”
Sub No_Code() If 1 = 2 Then Else MsgBox "something will happen because the statement is false.” End If End Sub
Similarly, if we decide to do something only when the statement is true, it would be in the following way:
Sub No_Code() If 1 = 1 Then MsgBox "something will happen because the statement is true.” Else End If End Sub
Example 2: Skip Iteration
In this example, we want to do nothing by skipping an iteration in a loop. We do this by rerouting the flow of the execution of our code to a bookmark that is placed right before the looping keyword.
Let’s assume we are looping x from 1 to 5. We will not do anything if X is less than 3, otherwise, we display a message stating the value of x. The statement ‘if X < 3 Then GoTo skipX
’ will move the flow of the code to the bookmark skipX
, which is right at the Next X
statement. The same strategy can be used for any other type of loop.
Sub Skip_Iteration() For X = 1 To 5 If X < 3 Then GoTo skipX MsgBox X skipX: Next X End Sub
Summary
Doing nothing in VBA is as simple as not writing any code, or re-routing the flow of code so that you skip all the things that otherwise the code would have done.
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…Then…Else и функция IIf, используемые в коде VBA Excel — синтаксис, компоненты, примеры.
Оператор If…Then…Else предназначен для передачи управления одному из блоков операторов в зависимости от результатов проверяемых условий.
Однострочная конструкция
Оператор If…Then…Else может использоваться в однострочной конструкции без ключевых слов Else, End If.
Синтаксис однострочной конструкции If…Then…
If [условие] Then [операторы] |
Компоненты однострочной конструкции If…Then…
- условие — числовое или строковое выражение, возвращающее логическое значение True или False;
- операторы — блок операторов кода VBA Excel, который выполняется, если компонент условие возвращает значение True.
Если компонент условие возвращает значение False, блок операторов конструкции If…Then… пропускается и управление программой передается следующей строке кода.
Пример 1
Sub Primer1() Dim d As Integer, a As String d = InputBox(«Введите число от 1 до 20», «Пример 1», 1) If d > 10 Then a = «Число « & d & » больше 10″ MsgBox a End Sub |
Многострочная конструкция
Синтаксис многострочной конструкции If…Then…Else
If [условие] Then [операторы] ElseIf [условие] Then [операторы] ———————— Else [операторы] End If |
Компоненты многострочной конструкции If…Then…Else:
- условие — числовое или строковое выражение, следующее за ключевым словом If или ElseIf и возвращающее логическое значение True или False;
- операторы — блок операторов кода VBA Excel, который выполняется, если компонент условие возвращает значение True;
- пунктирная линия обозначает дополнительные структурные блоки из строки
ElseIf [условие] Then
и строки[операторы]
.
Если компонент условие возвращает значение False, следующий за ним блок операторов конструкции If…Then…Else пропускается и управление программой передается следующей строке кода.
Самый простой вариант многострочной конструкции If…Then…Else:
If [условие] Then [операторы] Else [операторы] End If |
Пример 2
Sub Primer2() Dim d As Integer, a As String d = InputBox(«Введите число от 1 до 40», «Пример 2», 1) If d < 11 Then a = «Число « & d & » входит в первую десятку» ElseIf d > 10 And d < 21 Then a = «Число « & d & » входит во вторую десятку» ElseIf d > 20 And d < 31 Then a = «Число « & d & » входит в третью десятку» Else a = «Число « & d & » входит в четвертую десятку» End If MsgBox a End Sub |
Функция IIf
Функция IIf проверяет заданное условие и возвращает значение в зависимости от результата проверки.
Синтаксис функции
IIf([условие], [если True], [если False]) |
Компоненты функции IIf
- условие — числовое или строковое выражение, возвращающее логическое значение True или False;
- если True — значение, которое возвращает функция IIf, если условие возвратило значение True;
- если False — значение, которое возвращает функция IIf, если условие возвратило значение False.
Компоненты если True и если False могут быть выражениями, значения которых будут вычислены и возвращены.
Пример 3
Sub Primer3() Dim d As Integer, a As String Instr: On Error Resume Next d = InputBox(«Введите число от 1 до 20 и нажмите OK», «Пример 3», 1) If d > 20 Then GoTo Instr a = IIf(d < 10, d & » — число однозначное», d & » — число двузначное») MsgBox a End Sub |
Пример 4
Стоит отметить, что не зависимо от того, выполняется условие или нет, функция IIf вычислит оба выражения в параметрах если True и если False:
Sub Primer4() On Error GoTo Instr Dim x, y x = 10 y = 5 MsgBox IIf(x = 10, x + 5, y + 10) MsgBox IIf(x = 10, x + 5, y / 0) Exit Sub Instr: MsgBox «Произошла ошибка: « & Err.Description End Sub |
При нажатии кнопки «Cancel» или закрытии крестиком диалогового окна InputBox из первых двух примеров, генерируется ошибка, так как в этих случаях функция InputBox возвращает пустую строку. Присвоение пустой строки переменной d типа Integer вызывает ошибку. При нажатии кнопки «OK» диалогового окна, числа, вписанные в поле ввода в текстовом формате, VBA Excel автоматически преобразует в числовой формат переменной d. В третьем примере есть обработчик ошибок.
Grilled Giardiniera-Stuffed Steak Sandwich
This rolled flank steak is inspired by the Italian beef sandwich, a Chicago delicacy typically consisting of chopped thin slices of roast beef stuffed…
Provided by Food Network Kitchen
Mapo Potato
Let’s be clear: Nothing surpasses the hearty deliciousness of a traditional mapo tofu. But for those days when you find yourself without soft tofu in the…
Provided by Hetty McKinnon
Chili
This is a spicy, smoky and hearty pot of chili. It’s the kind of chili you need after a long day skiing — or hibernating. To create a rich and thick sauce,…
Provided by Ali Slagle
Banket
This recipe is from my mother. It is the one she taught me with a slight tweak. In my home on the holidays one way to show someone or a family they were…
Provided by Jena Lewis
Moroccan Nachos
This Moroccan twist on the much-loved appetizer features kefta, a ground beef (or lamb) mixture seasoned with parsley, cilantro, mint, paprika and cumin,…
Provided by Nargisse Benkabbou
Peanut Butter Brownie Cups
I’m not a chocolate fan (atleast not the kind made in the U.S.), but I LOVE peanut butter and chocolate and this hit the spot. I found the recipe in 2007…
Provided by AmyZoe
Banana Cream Pudding
This fabulous version of the favorite Southern dessert boosts the banana flavor by infusing it into the homemade vanilla pudding, in addition to the traditional…
Provided by Martha Stewart
Lemon Russian Tea Cakes
I love lemon desserts,these are a simple cookie I can make quickly. The recipe is based on the pecan Russian tea cakes.I don’t like lemon extract,instead…
Provided by Stephanie L. @nurseladycooks
Easy Churros with Mexican Chocolate Sauce
Forgo the traditional frying — and mixing up the batter! — for this Latin American treat. Instead, bake store-bought puff pastry for churros that are…
Provided by Martha Stewart
Easy Lasagna
Everyone loves lasagna. It’s perfect for feeding a big crowd and a hit at potlucks. But most people reserve it for a weekend cooking project since it can…
Provided by Food Network Kitchen
Grilled Vegetables Korean-Style
Who doesn’t love grilled vegetables — the sauce just takes them over the top.
Provided by Daily Inspiration S @DailyInspiration
Outrageous Chocolate Cookies
From Martha Stewart. I’m putting this here for safe keeping. This is a chocolate cookie with chocolate chunks. Yum! Do not over cook this cookie since…
Provided by C. Taylor
CERTO® Citrus Jelly
A blend of freshly squeezed orange and lemon juices puts the citrusy deliciousness in this CERTO Citrus Jelly.
Provided by My Food and Family
Previous
Next
VBA IF (IF THEN ELSE STATEMENT) — EXCEL CHAMPS
WebFeb 17, 2023 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 …
From excelchamps.com
Feb 17, 2023 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 …»>
See details
IF/ELSE THEN DO NOTHING IN EXCEL VBA — VBA AND VB.NET …
WebOct 30, 2020 VBA does not have a specific statement that can be used for ‘doing nothing ’. Unlike Python, which has a pass statement that can be placed where we do not want …
From software-solutions-online.com
Estimated Reading Time 2 mins
Oct 30, 2020 VBA does not have a specific statement that can be used for ‘doing nothing ’. Unlike Python, which has a pass statement that can be placed where we do not want …»>
See details
EXCEL — DO NOTHING IN VBA — STACK OVERFLOW
WebJul 8, 2018 In VBA, I find myself creating a dummy variable (sometimes a global) dim dummy as integer and then when I need that ‘do nothing’ action in an If..Then..Else I …
From stackoverflow.com
Reviews 6
Jul 8, 2018 In VBA, I find myself creating a dummy variable (sometimes a global) dim dummy as integer and then when I need that ‘do nothing‘ action in an If..Then..Else I …»>
See details
VBA IF VALUE IS NULL END SCRIPT ELSE CONTINUE — STACK OVERFLOW
WebJul 13, 2016 rightVal = RIGHT (xxxx.GetField («Col_2»), 4) If IsNull (rightVal) Or rightVal = «» Then Exit Sub End If If StrComp (XXXX.GetField («Col_1»), rightVal) <> 0 Then …
From stackoverflow.com
Jul 13, 2016 rightVal = RIGHT (xxxx.GetField («Col_2»), 4) If IsNull (rightVal) Or rightVal = «» Then Exit Sub End If If StrComp (XXXX.GetField («Col_1″), rightVal) <> 0 Then …»>
See details
HOW DO YOU MAKE YOUR ELSE STATEMENT DO NOTHING?
WebFeb 3, 2014 The usual do nothing statment is ; One example would be: for (var i=0; i<100; i++); // iterates to 100 but does nothing With that said, the else statement of an if is …
From stackoverflow.com
Feb 3, 2014 The usual do nothing statment is ; One example would be: for (var i=0; i<100; i++); // iterates to 100 but does nothing With that said, the else statement of an if is …»>
See details
IF, THEN, DO NOTHING? | MREXCEL MESSAGE BOARD
WebApr 11, 2014 If so, then the only way that can be done is with VBA if no, then you can use a function like this: Code: =If (A1= [condition], [change],A1) where you would have to set …
From mrexcel.com
Apr 11, 2014 If so, then the only way that can be done is with VBA if no, then you can use a function like this: Code: =If (A1= [condition], [change],A1) where you would have to set …»>
See details
IF VALUE NOT FOUND THEN … VBA — MICROSOFT COMMUNITY
WebDec 3, 2012 dinoname = InputBox(«what dinosaur do you want to be tested on??», «Dinotest») Set findrange = Range(«a2:a29») Set foundcell = findrange.Find(dinoname) If …
From answers.microsoft.com
Dec 3, 2012 dinoname = InputBox(«what dinosaur do you want to be tested on??», «Dinotest») Set findrange = Range(«a2:a29″) Set foundcell = findrange.Find(dinoname) If …»>
See details
[SOLVED] DO NOTHING IN VBA | 9TO5ANSWER
WebJul 9, 2022 Do nothing in vba vba excel 81,029 Solution 1 just remove pass and re run the code. VBA will be happy to accept that I believe Solution 2 Don’t include any …
From 9to5answer.com
Jul 9, 2022 Do nothing in vba vba excel 81,029 Solution 1 just remove pass and re run the code. VBA will be happy to accept that I believe Solution 2 Don’t include any …»>
See details
USING IF…THEN…ELSE STATEMENTS (VBA) | MICROSOFT LEARN
2023-04-09
From learn.microsoft.com
VBA ELSE IF STATEMENT | HOW TO USE EXCEL VBA ELSE IF STATEMENT?
WebVBA Else If allows you to analyze a condition, and perform an action accordingly. IF condition checks if the supplied condition is TRUE or FALSE, if the condition is TRUE it …
From educba.com
VBA Else If allows you to analyze a condition, and perform an action accordingly. IF condition checks if the supplied condition is TRUE or FALSE, if the condition is TRUE it …»>
See details
VBA IS NOTHING — AUTOMATE EXCEL
WebThe VBA Is Nothing statement uses the VBA “Is” Operator and checks to see an object has been assigned to an object variable. Sub CheckObject Dim rng as Range If rng Is …
From automateexcel.com
The VBA Is Nothing statement uses the VBA “Is” Operator and checks to see an object has been assigned to an object variable. Sub CheckObject Dim rng as Range If rng Is …»>
See details
IF A1 HAS CONTENT — RUN MACROA ELSE DO NOTHING …?
WebJan 23, 2015 1 Answer Sorted by: 2 Please try: Sub Macro1 () If WorksheetFunction.CountA (Range («A1»)) = 0 Then MsgBox «A1 is empty» Else …
From stackoverflow.com
Jan 23, 2015 1 Answer Sorted by: 2 Please try: Sub Macro1 () If WorksheetFunction.CountA (Range («A1»)) = 0 Then MsgBox «A1 is empty» Else …»>
See details
VBA IF BLANK DO NOTHING | MREXCEL MESSAGE BOARD
WebNov 13, 2015 tried If IsEmpty(Textbox1) Then Else If Textbox1.Value > 0 Then MsgBox «****» the message box also appears when textbox 1 is blank or i delete a value from it. …
From mrexcel.com
Nov 13, 2015 tried If IsEmpty(Textbox1) Then Else If Textbox1.Value > 0 Then MsgBox «****» the message box also appears when textbox 1 is blank or i delete a value from it. …»>
See details
VBA IF ELSE STATEMENT — HOW TO BUILD THE FORMULAS STEP BY STEP
WebDec 18, 2022 In a VBA if statement, each IF clause is separate from the other, and is instead laid out in order of priority from top to bottom. If Statement Structure in VBA If …
From corporatefinanceinstitute.com
Dec 18, 2022 In a VBA if statement, each IF clause is separate from the other, and is instead laid out in order of priority from top to bottom. If Statement Structure in VBA If …»>
See details
VBA IF — AND, OR, NOT — AUTOMATE EXCEL
WebTo check if the Profit is over $5,000, we can run the following macro: Sub CheckProfit () If Range («C5») >= 10000 And Range («C6») < 5000 Then MsgBox «$5,000 profit …
From automateexcel.com
To check if the Profit is over $5,000, we can run the following macro: Sub CheckProfit () If Range («C5») >= 10000 And Range («C6») < 5000 Then MsgBox «$5,000 profit …»>
See details
IF…THEN…ELSE STATEMENT — VISUAL BASIC | MICROSOFT LEARN
WebSep 14, 2021 If no elseifcondition evaluates to True, or if there are no ElseIf statements, the statements following Else are executed. After executing the statements following …
From learn.microsoft.com
Sep 14, 2021 If no elseifcondition evaluates to True, or if there are no ElseIf statements, the statements following Else are executed. After executing the statements following …»>
See details
NOTHING KEYWORD (VBA) | MICROSOFT LEARN
WebSep 13, 2021 The Nothing keyword is used to disassociate an object variable from an actual object. Use the Set statement to assign Nothing to an object variable. For …
From learn.microsoft.com
Sep 13, 2021 The Nothing keyword is used to disassociate an object variable from an actual object. Use the Set statement to assign Nothing to an object variable. For …»>
See details
IF…THEN…ELSE STATEMENT (VBA) | MICROSOFT LEARN
WebMar 29, 2022 If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement. The Else and ElseIf clauses are both …
From learn.microsoft.com
Mar 29, 2022 If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement. The Else and ElseIf clauses are both …»>
See details
VBA IF, ELSEIF, ELSE (ULTIMATE GUIDE TO IF STATEMENTS)
WebVBA 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 …
From automateexcel.com
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 …»>
See details
EXCEL — MACRO STILL RUNNING AFTER (MSGBOX VBYESNO) IF THEN …
WebFeb 26, 2020 End If Set fs = Nothing Set FileSystem = CreateObject («Scripting.FileSystemObject») DoFolder FileSystem.GetFolder (HostFolder) …
From stackoverflow.com
Feb 26, 2020 End If Set fs = Nothing Set FileSystem = CreateObject («Scripting.FileSystemObject») DoFolder FileSystem.GetFolder (HostFolder) …»>
See details
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:
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
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
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.)
In VBA, when you use the IF statement, you can use a GoTo statement to Exit the IF. Let me clarify here; there’s no separate exit statement that you can use with IF to exit. So, it would be best if you used goto to jump out of the IF before the line of the end statement reached.
Let’s look at an example to understand this.
In the above example, as you can see, we have used an IF statement to check if there’s a value in cell A1 or not. When you run this code, and there’s no value in the A1, VBA will jump to the “Lable1” and run the code under it. So, it will show an input box to enter the value in cell A1.
Sub myMacro()
If Range("A1") = "" Then
GoTo Lable1
Else
MsgBox "there's a value in the cell."
End If
Lable1:
Range("A1").Value = _
InputBox("Enter Value")
End Sub
There will be a few situations when you need to exit an IF statement while writing a VBA code. As you know in the single IF statement, there can only be two conditions, and if one condition is true, VBA will run the code that you have mentioned for it and then exit the statement automatically.