If then goto in excel

Инструкции безусловного перехода

С помощью инструкций безусловного перехода можно приступать к выполнению части заданной программы без проверки каких-либо условий. К таким инструкциям относятся GoTo и пара GoSub-Return. Однако перед их рассмотрением необходимо ознакомиться еще с одним элементом языка VBA, без которого данные инструкции использоваться не могут, – с метками.

Метки

Метка – это идентификатор VBA или целое число, которое располагается в начале строки и заканчивается двоеточием. Метки используются для указания строк, на которые можно переходить с помощью инструкций GoTo и GoSub. Примеры меток приведены ниже:

100:

DoSomeAction:

Перерасчет:

После перехода на метку выполняются все инструкции, расположенные после нее до конца процедуры, функции, следующих инструкций GoTo, GoSub или до инструкции Return (см. далее).

Инструкция GoTo

Инструкция GoTo используется для простого перехода к выполнению программы после нужной метки. Формат инструкции следующий:

GoTo Имя_метки

Инструкции, расположенные после GoTo, выполняются только в том случае, если в программе существуют соответствующие инструкции GoTo или GoSub. Рассмотрим пример использования GoTo:

a = 15 + b

If a < 0 Then GoTo 10

‘ Выполнение действий для значения переменной a больше нуля

10:

‘ Выполнение действий для значения переменной a меньше нуля

Следует отметить, что частое использование инструкции GoTo в программе не рекомендуется, так как может сделать алгоритм слишком запутанным. GoTo нередко допустимо заменить инструкциями выбора либо вызовом процедуры или функции.

Пара инструкций GoSub-Return

Во времена старого доброго языка Basic инструкции GoSub и Return были незаменимы для программиста. Это было связано с тем, что Basic не был даже процедурным языком программирования: в нем не было процедур и функций, все инструкции записывались в виде единой программы. Чтобы не реализовывать несколько раз одинаковые действия, в этой большой программе выделялись отрезки кода, выполняющие типичные действия, – подпрограммы. Подпрограмма начиналась некоторой меткой и оканчивалась инструкцией Return.

При достижении инструкции Go Sub осуществлялся переход на указанную метку (аналогично инструкции GoTo) – начинала выполняться подпрограмма. При достижении инструкции Return происходил возврат из подпрограммы – выполнение программы продолжалось после последней инструкции Go Sub.

Пара инструкций GoSub-Return в языке VBA работает точно таким же образом, но переходы осуществляются только в пределах процедуры или функции. Формат инструкций GoSub-Return такой:

GoSub Имя_метки

[Инструкции]

Имя_метки:

[Инструкции подпрограммы]

Return

Ниже приведен пример использования инструкций GoSub-Return (в подпрограмме вычисляется квадрат длины гипотенузы прямоугольного треугольника):

a = 5

b = 4

GoSub Calculate

‘ Другие действия

Calculate:

‘ Подпрограмма

c2 = a ^ 2 + b ^ 2

Return

Следует отметить, что при процедурном, а тем более объектно-ориентированном программировании необходимость использования подпрограмм полностью отпала. Роль подпрограмм выполняют функции и процедуры.

  • #2

Hi all

I have several macros on the go at the moment for work and I am trying to improve them somewhat.

The macros go into other spreadsheets and extract data from them.

The other spreadsheets all have general name formats based on their purpose/results/date or week of the year.

However, since they are manually saved files from other people, the file names are subject to errors etc. I generally try and account for this with multiple nested if statements to check for the correct file name based on the length function.

Example

Code:

If Len(Dir(ivrPath + FE)) = 0 Then 
    MsgBox "Finance Export Not Found - please make sure the file name is 'Finance Export DD.MM.YYYY.xls"
    Exit Sub
Else
    Workbooks.Open ivrPath + FE, , 1
End If

What I am wondering is if it possible to incorporate the GOTO command into the IF statement, eg set labels on each file open process, and then if the file name returns a zero length the GOTO command can be used to skip all the code associated with that worksheet and instead of exiting, open the next sheet in the list and start working on that…

My questions are…1) is this possible? & 2) I saw some comments that say the use of the GOTO command in programming is not best practice, so is there another way I should do this instead?

Thanks in advance for any help / information.

Regards
Patrick

couldn’t resist: (from xkcd)

goto.png

  • #5

The code gods will severely punish you if you do ;)

Dom

  • #6

Im not really sure it would qualify as spaghetti code, since the code is still linear, it simply bypasses sections associated with spreadsheets it cant open (and displays a warning message to the user)…

From the comments I gather that GOTO is a no-no, so any other suggestions on how I can do this?

Thanks :)

  • #7

Im not really sure it would qualify as spaghetti code, since the code is still linear, it simply bypasses sections associated with spreadsheets it cant open (and displays a warning message to the user)…

From the comments I gather that GOTO is a no-no, so any other suggestions on how I can do this?

Thanks :)

why can’t you just put all the code you want skipped in the else part of the if statment?

  • #8

Im not really sure it would qualify as spaghetti code, since the code is still linear, it simply bypasses sections associated with spreadsheets it cant open (and displays a warning message to the user)…

From the comments I gather that GOTO is a no-no, so any other suggestions on how I can do this?

Thanks :)

It’s a «Gateway Drug» similar to the grass like substance..
doing it one time is not spaghetti…It’s just one Noodle.
Once you say «it’s okay to do it once»…
«Well, if it’s okay once, then 2 or three is fine»
«if 2 or 3 is fine, why not a dozen…
Then you have several noodles.
Before you know it, you have spaghetti and a full blown addiction to fractures in concrete.

That’s why it’s best to follow «Best Practices» all the time, even for the quick simple codes.

  • #9

It’s a «Gateway Drug» similar to the grass like substance..
doing it one time is not spaghetti…It’s just one Noodle.
Once you say «it’s okay to do it once»…
«Well, if it’s okay once, then 2 or three is fine»
«if 2 or 3 is fine, why not a dozen…
Then you have several noodles.
Before you know it, you have spaghetti and a full blown addiction to fractures in concrete.

That’s why it’s best to follow «Best Practices» all the time, even for the quick simple codes.

plus, if you can figure out how to avoid a goto in an easy bit of code, then you’re building the experience to be able to write well-structured code when you have larger coding projects.

  • #10

‘On Error Goto ErrorHandler’ is more than acceptable if you can set up a suitable trap and handler.

Dom

You did not define the label playerRollingForHit… at least not in the code you are showing. This is a problem.

As was pointed out by others, not having an idea of code structure is a much bigger problem. A GoTo statement, while legal should be used sparingly. And you should consider making your code more re-usable. For example, you can create your own data type:

Public Type player
  health As Integer
  strength As Integer
  ' whatever other properties you might have...
End Type

And then you can create an array of players:

Dim players( 1 To 2 ) as player

This means you will be able to loop over the players, and «player 1 attacks player 2» can use the same code as «player 2 attacks player 1» (if they have the same rules). Similarly, you might want to create your own function «rollBetween» which allows you to roll different dice with a simple instruction.

Function rollBetween(n1 As Integer, n2 As Integer)
' roll a number between n1 and n2, inclusive
rollBetween = Round(Rnd * (n2 - n1 + 1) - 0.5, 0) + n1
End Function

Putting it all together, for fun, I created some code that may help you understand what I’m talking about. Note — the rules here are not the same rules you used, but it’s the same principle; as players get more strength, they become more immune to attack, and their attacks become stronger. I hope you can learn something from it, and have fun creating your game!

Option Explicit

Public Type player
  health As Integer
  strength As Integer
End Type

Sub monsters()
' main program loop
' can have more than two players: just change dimension of array
' and rules of "who attacks whom"
Dim players(1 To 2) As player
Dim attacker As Integer
Dim defender As Integer

initPlayers players
attacker = rollBetween(1, 2) ' who goes first: player 1 or 2
Debug.Print "Player " & attacker & " gets the first roll"

While stillAlive(players)
  defender = (attacker Mod 2) + 1
  playTurn players, attacker, defender
  attacker = defender  ' person who was attacked becomes the attacker
Wend

MsgBox winner(players())

End Sub

'------------------------------
' functions that support the main program loop 'monsters':

Function rollBetween(n1 As Integer, n2 As Integer)
' roll a number between n1 and n2, inclusive
rollBetween = Round(Rnd * (n2 - n1 + 1) - 0.5, 0) + n1
End Function

Sub initPlayers(ByRef p() As player)
' initialize the strength of the players etc
Dim ii
For ii = LBound(p) To UBound(p)
  p(ii).health = 10
  p(ii).strength = 1
Next

End Sub

Function stillAlive(p() As player) As Boolean
' see whether players are still alive
' returns false if at least one player's health is less than 0
Dim ii
For ii = LBound(p) To UBound(p)
  If p(ii).health <= 0 Then
    stillAlive = False
    Exit Function
  End If
Next ii
stillAlive = True
End Function

Sub playTurn(ByRef p() As player, n As Integer, m As Integer)
' attack of player(n) on player(m)
Dim roll As Integer

' see if you can attack, or just heal:
roll = rollBetween(1, 2)
Debug.Print "player " & n & " rolled a " & roll

If roll = 1 Then
  ' roll for damage
  roll = rollBetween(1, 4 + p(n).strength)  ' as he gets stronger, attacks become more damaging
  Debug.Print "player " & n & " rolled a " & roll & " for attack"
  If p(m).strength > roll Then
    p(n).strength = p(n).strength - 1 ' attacker gets weaker because attack failed
    p(m).strength = p(m).strength + 2 ' defender gets stronger
  Else
    p(n).strength = p(n).strength + 1 ' attacker gains strength
    p(m).health = p(m).health - roll  ' defender loses health
  End If
Else
  ' roll for healing
  roll = rollBetween(1, 3)
  Debug.Print "player " & n & " rolled a " & roll & " for health"
  p(n).health = p(n).health + roll
End If
Debug.Print "statistics now: " & p(1).health & "," & p(1).strength & ";" & p(2).health & "," & p(2).strength

End Sub

Function winner(p() As player)
Dim ii, h, w
' track player with higher health:
h = 0
w = 0

For ii = LBound(p) To UBound(p)
  If p(ii).health > h Then
    w = ii
    h = p(ii).health
  End If
Next ii

winner = "Player " & w & " is the winner!"

End Function

Output of a typical game might be:

Player 2 gets the first roll
player 2 rolled a 2
player 2 rolled a 2 for health
statistics now: 10,1;12,1
player 1 rolled a 1
player 1 rolled a 2 for attack
statistics now: 10,2;10,1
player 2 rolled a 2
player 2 rolled a 1 for health
statistics now: 10,2;11,1
player 1 rolled a 2
player 1 rolled a 3 for health
statistics now: 13,2;11,1
player 2 rolled a 2
player 2 rolled a 1 for health
statistics now: 13,2;12,1
player 1 rolled a 1
player 1 rolled a 6 for attack
statistics now: 13,3;6,1
player 2 rolled a 2
player 2 rolled a 2 for health
statistics now: 13,3;8,1
player 1 rolled a 2
player 1 rolled a 3 for health
statistics now: 16,3;8,1
player 2 rolled a 1
player 2 rolled a 5 for attack
statistics now: 11,3;8,2
player 1 rolled a 1
player 1 rolled a 4 for attack
statistics now: 11,4;4,2
player 2 rolled a 2
player 2 rolled a 1 for health
statistics now: 11,4;5,2
player 1 rolled a 2
player 1 rolled a 2 for health
statistics now: 13,4;5,2
player 2 rolled a 1
player 2 rolled a 4 for attack
statistics now: 9,4;5,3
player 1 rolled a 2
player 1 rolled a 1 for health
statistics now: 10,4;5,3
player 2 rolled a 1
player 2 rolled a 6 for attack
statistics now: 4,4;5,4
player 1 rolled a 2
player 1 rolled a 2 for health
statistics now: 6,4;5,4
player 2 rolled a 2
player 2 rolled a 3 for health
statistics now: 6,4;8,4
player 1 rolled a 1
player 1 rolled a 6 for attack
statistics now: 6,5;2,4
player 2 rolled a 2
player 2 rolled a 1 for health
statistics now: 6,5;3,4
player 1 rolled a 2
player 1 rolled a 1 for health
statistics now: 7,5;3,4
player 2 rolled a 2
player 2 rolled a 3 for health
statistics now: 7,5;6,4
player 1 rolled a 1
player 1 rolled a 6 for attack
statistics now: 7,6;0,4

Final output — message box that declares player 1 the winner.

Однострочная и многострочная конструкции оператора 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. В третьем примере есть обработчик ошибок.


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:

using VBA IF statement code in excel

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

vba if statement using if then macro code

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
vba if statement using if then else macro code

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:

  1. A condition to evaluate.
  2. A statement to perform if that condition is TURE.
  3. If that condition is FALSE then we have the second condition to evaluate.
  4. And, if the second condition is TRUE we have a statement to perform.
  5. 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

vba if statement using if then elseif else macro code
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.

writing nesting if with vba if statement
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.

using vba if statement to check number in cell
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.

using vba if statement with checkbox
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.

check if a cell is merged using vba if statement
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

Понравилась статья? Поделить с друзьями:
  • If then else vba excel примеры
  • If then else for vba excel
  • If then else excel with and
  • If then and if then else excel
  • If the word was ending перевод