Excel vba if starts with

While developing code, there are many situations where you might need to validate if a string begins with some specific characters (another string).

For example, take this scenario: A company named XYZ allocates employee IDs starting with the abbreviation of the department name. If that employee tries to use his employee ID and login for the company’s intranet site or corporate medical insurance site, the portal might validate this ID.

Let’s assume an employee named Rahul is allocated the Employee ID “GBS000493” since he works for “Global Business Services” department. Now if he tries to login into his corporate medical insurance portal, the login button will validate if his Employee ID is valid.

StartsWith() does the trick… for Java

Some programming languages like Java offer a built-in method named “StartsWith()” that uses a couple of mandatory parameters (the string to be validated and the piece of the string which should be looked for in the beginning) and returns a Boolean value to indicate the validation result.

However, VBA does not offer any such straightforward methods to validate the prefix of a string. So what can we do?

Alternate methods in VBA to validate the prefix of a string

Here are some interesting built-in methods which help us achieve our goal of validating a string’s prefix.

The Instr method

The Instr method finds if one string exists inside another string and returns the position at which it is found. If the string is not found, it returns 0.

Syntax:

InStr([ < start > ], < string 1 >, < string 2 >, [ < compare > ])

Where

Start is an optional numeric value that indicates the starting position of the search.

String 1 is the string expression that is being searched

String 2 is the string expression that is being searched for within string 1

Compare indicates the type of string comparison. Your string comparison type could be any one of the following below. Note that this is an optional parameter, though.

Constant Value Description
vbUseCompareOption -1 Comparision is done by using the Option Compare statement’s setting.
vbBinaryCompare 0 Binary comparison is done.
vbTextCompare 1 Textual comparison is done.
vbDatabaseCompare 2 This option is only for Microsoft Access. A comparison is done based on information in our database.

Example

This function can be used as shown in the code below to work similarly to the “StartsWith” method. A value of “1” has to be provided as the value for “starts” parameter.

Sub startswith_demo()
  
    'declaration of variables
    Dim string1, string2
    
    'assigning values
    string1 = "India is my country"
    string2 = "India"
    
    'Validate and print if string 1 begins with string2
    flag = InStr(1, string1, string2)
    If flag = 1 Then
        Debug.Print True
    Else
        Debug.Print False
    End If
    
End Sub

True is returned in example using the InStr method

The Left method in combination with the Len method

Left function

The Left() method extracts a specific number of characters from the left side of a string starting from the first character.

Syntax:

Left( < string expression > , < no of characters > )

For example:

Msgbox Left(“Lioness”,4) 

would display “Lion” in a message box.

Len function

The Len() function returns the number of characters in a string.

Syntax:

Len ( < string expression > )

For example:

Msgbox Len(“Lioness”)

Would display “7” in a message box.

Using these two built-in functions, we can define a new user-defined StartsWith function to meet our requirements.

Sub startswith_demo()
  
    'declaration of variables
    Dim string1 As String, string2 As String, string3 As String
    
    'assigning values
    string1 = "India is my country"
    string2 = "India"
    string3 = "Big"
    
    'Validate and print if string 1 begins with string2
    
    If StartsWith(string1, string2) = True Then
        Debug.Print True
    Else
        Debug.Print False
    End If
    
    'Validate and print if string 1 begins with string3
    
    If StartsWith(string1, string3) = True Then
        Debug.Print True
    Else
        Debug.Print False
    End If
    
End Sub

Public Function StartsWith(str As String, str_prefix As String) As Boolean
    StartsWith = Left(str, Len(str_prefix)) = str_prefix
End Function

Example with a user defined function using len and left to mimic startswith

The Mid method in combination with the Len method

Mid function

The mid() function is used to grab any subsection of a string

Syntax:

MID( < string expression > , < starting position > , [ < number of characters > ] )

For example:

Msgbox Mid(“This is a long queue”,6,2)

Would display “is” in a message box.

So, we can use the Mid function along with the Len function (explained in the previous example) to clip the first few characters of the string. We can find the length of the string that is going to be the prefix.

Sub startswith_demo()
  
    'declaration of variables
    Dim str_full As String, str_true As String, str_false As String
    
    'assigning values
    str_full = "I am out of country"
    str_true = "country"
    str_false = "I am"
    
    'Validate and print if str_full begins with str_true
    
    If StartsWith(str_full, str_true) = True Then
        Debug.Print True
    Else
        Debug.Print False
    End If
    
    'Validate and print if str_full begins with str_false
    
    If StartsWith(str_full, str_false) = True Then
        Debug.Print True
    Else
        Debug.Print False
    End If
    
End Sub

Public Function StartsWith(str As String, str_prefix As String) As Boolean
    StartsWith = Mid(str, 1, Len(str_prefix)) = str_prefix
End Function

Example using Len and Mid for user defined function

The Like keyword

This comparison operator works like it would in a structured query language. It helps us easily validate the pattern of the string from any position.

Syntax:

< string expression > Like < pattern >)

For example:

Msgbox  ( “Hello World” Like “Hel*”)

Would display “True” in the message box.

So, we can make use of this comparison operator to benefit from the functionality that “StartsWith” method offers in other programming languages.

Sub startswith_demo()
  
    'declaration of variables
    Dim str_full As String, str_short As String
    
    'assigning values
    str_full = "I am out of country"
    str_short = "country"
    
    'Validate and print if str_full begins with str_short
    
    If str_full Like str_true &amp;amp;amp; "*" Then
        Debug.Print "Yes, it starts with the mentioned prefix"
    Else
        Debug.Print "No, it does not start with the mentioned prefix"
    End If
    
    'validate directly without variables
    
    If "Taj Mahal is in India" Like "Taj*" Then
        Debug.Print "The sentence starts with the expected text"
    Else
        Debug.Print "The sentence does not start with the expected text"
    End If
    
    'validate again with a negative scenario
    If "Welcome on board" Like "board*" Then
        Debug.Print "The sentence starts with the expected text"
    Else
        Debug.Print "The sentence does not start with the expected text"
    End If   
    
End Sub

Example using the like operator

Conclusion

Though the exact method “StartsWith()” is not offered by Microsoft in VBA, there are several other alternate built-in functions that can be easily customized to quickly achieve what we want.

In this article , we discussed a few of them. Of these, the “Like” operator can be used to validate the beginning of any string without much strain, coding, or technical knowledge.

There might even be more ways to achieve this same goal! Let us know if this gets your juices flowing, and add your suggestions to the comments below.

This post provides a complete guide to the VBA If Statement in VBA. If you are looking for the syntax then check out the quick guide in the first section which includes some examples.

The table of contents below provides an overview of what is included in the post. You use this to navigate to the section you want or you can read the post from start to finish.

“Guess, if you can, and choose, if you dare.” – Pierre Corneille

Quick Guide to the VBA If Statement

Description Format Example
If Then If [condition is true] Then
    [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
End If
If Else If [condition is true] Then
    [do something]
Else
    [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
Else
       Debug.Print «Try again»
End If
If ElseIf If [condition 1 is true] Then
    [do something]
ElseIf [condition 2 is true] Then
    [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
ElseIf score > 50 Then
       Debug.Print «Passed»
ElseIf score <= 50 Then
       Debug.Print «Try again»
End If
Else and ElseIf
(Else must come
after ElseIf’s)
If [condition 1 is true] Then
      [do something]
ElseIf [condition 2 is true] Then
      [do something]
Else
      [do something]
End If
If score = 100 Then
       Debug.Print «Perfect»
ElseIf score > 50 Then
       Debug.Print «Passed»
ElseIf score > 30 Then
       Debug.Print «Try again»
Else
       Debug.Print «Yikes»
End If
If without Endif
(One line only)
If [condition is true] Then [do something] If value <= 0 Then value = 0

The following code shows a simple example of using the VBA If statement

If Sheet1.Range("A1").Value > 5 Then
    Debug.Print "Value is greater than five."
ElseIf Sheet1.Range("A1").Value < 5 Then
    Debug.Print "value is less than five."
Else
    Debug.Print "value is equal to five."
End If

The Webinar

Members of the Webinar Archives can access the webinar for this article by clicking on the image below.

(Note: Website members have access to the full webinar archive.)

What is the VBA If Statement

The VBA If statement is used to allow your code to make choices when it is running.

You will often want to make choices based on the data your macros reads.

For example, you may want to read only the students who have marks greater than 70. As you read through each student you would use the If Statement to check the marks of each student.

The important word in the last sentence is check. The If statement is used to check a value and then to perform a task based on the results of that check.

The Test Data and Source Code

We’re going to use the following test data for the code examples in this post:

VBA If Sample Data

You can download the test data with all the source code for post plus the solution to the exercise at the end:

Format of the VBA If-Then Statement

The format of the If Then statement is as follows

If [condition is true] Then

The If keyword is followed by a Condition and the keyword Then

Every time you use an If Then statement you must use a matching End If statement.
When the condition evaluates to true, all the lines between If Then and End If are processed.

If [condition is true] Then
    [lines of code]
    [lines of code]
    [lines of code]
End If

To make your code more readable it is good practice to indent the lines between the If Then and End If statements.

Indenting Between If and End If

Indenting simply means to move a line of code one tab to the right. The rule of thumb is to indent between start and end statements like

Sub … End Sub
If Then … End If
If Then… ElseIf … Else … Endif
For … Next
Do While … Loop
Select Case … End Case

To indent the code you can highlight the lines to indent and press the Tab key. Pressing Shift + Tab will Outdent the code i.e. move it one tab to the left.

You can also use the icons from the Visual Basic Toolbar to indent/outdent the code

VBA If

Select code and click icons to indent/outdent

If you look at any code examples on this website you will see that the code is indented.

A Simple If Then Example

The following code prints out the names of all students with marks greater than 50 in French.

' https://excelmacromastery.com/
Sub ReadMarks()
    
    Dim i As Long
    ' Go through the marks columns
    For i = 2 To 11
        ' Check if marks greater than 50
        If Sheet1.Range("C" & i).Value > 50 Then
            ' Print student name to the Immediate Window(Ctrl + G)
            Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value
        End If
    
    Next
    
End Sub

Results
Bryan Snyder
Juanita Moody
Douglas Blair
Leah Frank
Monica Banks

Play around with this example and check the value or the > sign and see how the results change.

Using Conditions with the VBA If Statement

The piece of code between the If and the Then keywords is called the condition. A condition is a statement that evaluates to true or false. They are mostly used with Loops and If statements. When you create a condition you use signs like >,<,<>,>=,<=,=.

The following are examples of conditions

Condition This is true when
x < 5 x is less than 5
x <= 5 x is less than or equal to 5
x > 5 x is greater than 5
x >= 5 x is greater than or equal to 5
x = 5 x is equal to 5
x <> 5 x does not equal 5
x > 5 And x < 10 x is greater than 5 AND x is less than 10
x = 2 Or x >10 x is equal to 2 OR x is greater than 10
Range(«A1») = «John» Cell A1 contains text «John»
Range(«A1») <> «John» Cell A1 does not contain text «John»

You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.

When equals is used in a condition it means “is the left side equal to the right side”.

The following table demonstrates how the equals sign is used in conditions and assignments

Using Equals Statement Type Meaning
Loop Until x = 5 Condition Is x equal to 5
Do While x = 5 Condition Is x equal to 5
If x = 5 Then Condition Is x equal to 5
For x = 1 To 5 Assignment Set the value of x to 1, then to 2 etc.
x = 5 Assignment Set the value of x to 5
b = 6 = 5 Assignment and Condition Assign b to the result of condition 6 = 5
x = MyFunc(5,6) Assignment Assign x to the value returned from the function

The last entry in the above table shows a statement with two equals. The first equals sign is the assignment and any following equals signs are conditions.

This might seem confusing at first but think of it like this. Any statement that starts with a variable and an equals is in the following format

[variable] [=] [evaluate this part]

So whatever is on the right of the equals sign is evaluated and the result is placed in the variable. Taking the last three assignments again, you could look at them like this

[x] [=] [5]
[b] [=] [6 = 5]
[x] [=] [MyFunc(5,6)]

Using ElseIf with the VBA If Statement

The ElseIf statement allows you to choose from more than one option. In the following example we print for marks that are in the Distinction or High Distinction range.

' https://excelmacromastery.com/
Sub UseElseIf()
    
    If Marks >= 85 Then
        Debug.Print "High Destinction"
    ElseIf Marks >= 75 Then
        Debug.Print "Destinction"
    End If
    
End Sub

The important thing to understand is that order is important. The If condition is checked first.
If it is true then “High Distinction” is printed and the If statement ends.
If it is false then the code moves to the next ElseIf and checks it condition.

Let’s swap around the If and ElseIf from the last example. The code now look like this

' https://excelmacromastery.com/
Sub UseElseIfWrong()
    
    ' This code is incorrect as the ElseIf will never be true
    If Marks >= 75 Then
        Debug.Print "Destinction"
    ElseIf Marks >= 85 Then
        ' code will never reach here
        Debug.Print "High Destinction"
    End If
    
End Sub

In this case we check for a value being over 75 first. We will never print “High Distinction” because if a value is over 85 is will trigger the first if statement.

To avoid these kind of problems we should use two conditions. These help state exactly what you are looking for a remove any confusion. The example below shows how to use these. We will look at more multiple conditions in the section below.

If marks >= 75 And marks < 85 Then
    Debug.Print "Destinction"
ElseIf marks >= 85 And marks <= 100 Then
    Debug.Print "High Destinction"
End If

Let’s expand the original code. You can use as many ElseIf statements as you like. We will add some more to take into account all our mark classifications.

If you want to try out these examples you can download the code from the top of this post.

Using Else With the VBA If Statement

The VBA Else statement is used as a catch all. It basically means “if no conditions were true” or “everything else”. In the previous code example, we didn’t include a print statement for a fail mark. We can add this using Else.

' https://excelmacromastery.com/
Sub UseElse()
    
    If Marks >= 85 Then
        Debug.Print "High Destinction"
    ElseIf Marks >= 75 Then
        Debug.Print "Destinction"
    ElseIf Marks >= 55 Then
        Debug.Print "Credit"
    ElseIf Marks >= 40 Then
        Debug.Print "Pass"
    Else
        ' For all other marks
        Debug.Print "Fail"
    End If
    
End Sub

So if it is not one of the other types then it is a fail.

Let’s write some code to go through our sample data and print the student and their classification:

' https://excelmacromastery.com/
Sub AddClass()
    
    ' get the last row
    Dim startRow As Long, lastRow As Long
    startRow = 2
    lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, Marks As Long
    Dim sClass As String

    ' Go through the marks columns
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Check marks and classify accordingly
        If Marks >= 85 Then
            sClass = "High Destinction"
        ElseIf Marks >= 75 Then
            sClass = "Destinction"
        ElseIf Marks >= 55 Then
            sClass = "Credit"
        ElseIf Marks >= 40 Then
            sClass = "Pass"
        Else
            ' For all other marks
            sClass = "Fail"
        End If
    
        ' Write out the class to column E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

The results look like this with column E containing the classification of the marks

VBA If ElseIf Class

Results

Remember that you can try these examples for yourself with the code download from the top of this post.

Using Logical Operators with the VBA If Statement

You can have more than one condition in an If Statement. The VBA keywords And and Or allow use of multiple conditions.

These words work in a similar way to how you would use them in English.

Let’s look at our sample data again. We now want to print all the students that got over between 50 and 80 marks.
We use And to add an extra condition. The code is saying: if the mark is greater than or equal 50 and less than 75 then print the student name.

' https://excelmacromastery.com/
Sub CheckMarkRange()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Store marks for current student
        marks = Sheet1.Range("C" & i).Value
        
        ' Check if marks greater than 50 and less than 75
        If marks >= 50 And marks < 80 Then
             ' Print first and last name to Immediate window(Ctrl G)
             Debug.Print Sheet1.Range("A" & i).Value & Sheet1.Range("B" & i).Value
        End If
    
    Next

End Sub

Results
Douglas Blair
Leah Frank
Monica Banks

In our next example we want the students who did History or French. So in this case we are saying if the student did History OR if the student did French:

' Description: Uses OR to check the study took History or French.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub UseOr()
    
    ' Get the data range
    Dim rg As Range
    Set rg = shMarks.Range("A1").CurrentRegion

    Dim i As Long, subject As String
    
    ' Read through the data
    For i = 2 To rg.Rows.Count
    
        ' Get the subject
        subject = rg.Cells(i, 4).Value
        
        ' Check if subject greater than 50 and less than 80
        If subject = "History" Or subject = "French" Then
            ' Print first name and subject to Immediate window(Ctrl G)
            Debug.Print rg.Cells(i, 1).Value & " " & rg.Cells(i, 4).Value
        End If
    
    Next
    
End Sub

Results
Bryan History
Bradford French
Douglas History
Ken French
Leah French
Rosalie History
Jackie History

Using Multiple conditions like this is often a source of errors. The rule of thumb to remember is to keep them as simple as possible.

Using If And

The AND works as follows

Condition 1 Condition 2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

What you will notice is that AND is only true when all conditions are true

Using If Or

The OR keyword works as follows

Condition 1 Condition 2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

What you will notice is that OR is only false when all the conditions are false.

Mixing AND and OR together can make the code difficult to read and lead to errors. Using parenthesis can make the conditions clearer.

' https://excelmacromastery.com/
Sub OrWithAnd()
    
 Dim subject As String, marks As Long
 subject = "History"
 marks = 5
    
 If (subject = "French" Or subject = "History") And marks >= 6 Then
     Debug.Print "True"
 Else
     Debug.Print "False"
 End If
    
End Sub

Using If Not

There is also a NOT operator. This returns the opposite result of the condition.

Condition Result
TRUE FALSE
FALSE TRUE

The following two lines of code are equivalent.

If marks < 40 Then 
If Not marks >= 40 Then

as are

If True Then 
If Not False Then 

and

If False Then 
If Not True Then 

Putting the condition in parenthesis makes the code easier to read

If Not (marks >= 40) Then

A common usage of Not when checking if an object has been set. Take a worksheet for example. Here we declare the worksheet

Dim mySheet As Worksheet
' Some code here

We want to check mySheet is valid before we use it. We can check if it is nothing.

If mySheet Is Nothing Then

There is no way to check if it is something as there is many different ways it could be something. Therefore we use Not with Nothing

If Not mySheet Is Nothing Then

If you find this a bit confusing you can use parenthesis like this

If Not (mySheet Is Nothing) Then

The IIF function

Note that you can download the IIF examples below and all source code from the top of this post.

VBA has an fuction similar to the Excel If function. In Excel you will often use the If function as follows:

=IF(F2=””,””,F1/F2)

The format is

=If(condition, action if true, action if false).

VBA has the IIf statement which works the same way. Let’s look at an example. In the following code we use IIf to check the value of the variable val. If the value is greater than 10 we print true otherwise we print false:

' Description: Using the IIF function to check a number.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub CheckNumberIIF()
 
    Dim result As Boolean
    Dim number As Long
    
    ' Prints True
    number = 11
    result = IIf(number > 10, True, False)
    Debug.Print "Number " & number & " greater than 10 is " & result
    
    ' Prints false
    number = 5
    result = IIf(number > 10, True, False)
    Debug.Print "Number " & number & " greater than 10 is " & result
    
End Sub

In our next example we want to print out Pass or Fail beside each student depending on their marks. In the first piece of code we will use the normal VBA If statement to do this:

' https://excelmacromastery.com/
Sub CheckMarkRange()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Store marks for current student
        marks = Sheet1.Range("C" & i).Value
        
        ' Check if student passes or fails
        If marks >= 40 Then
             ' Write out names to to Column F
             Sheet1.Range("E" & i) = "Pass"
        Else
             Sheet1.Range("E" & i) = "Fail"
        End If
    
    Next

End Sub

In the next piece of code we will use the IIf function. You can see that the code is much neater here:

' Description: Using the IIF function to check marks.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub CheckMarkRange()

    ' Get the data range
    Dim rg As Range
    Set rg = shMarks.Range("A1").CurrentRegion
    
    Dim i As Long, marks As Long, result As String
    ' Go through the marks columns
    For i = 2 To rg.Rows.Count
        
        ' Store marks for current student
        marks = rg.Cells(i, 3).Value
        
        ' Check if student passes or fails
        result = IIf(marks >= 40, "Pass", "Fail")
        
        ' Print the name and result
        Debug.Print rg.Cells(i, 1).Value, result
    
    Next

End Sub

You can see the IIf function is very useful for simple cases where you are dealing with two possible options.

Using Nested IIf

You can also nest IIf statements like in Excel. This means using the result of one IIf with another. Let’s add another result type to our previous examples. Now we want to print Distinction, Pass or Fail for each student.

Using the normal VBA we would do it like this

' https://excelmacromastery.com/
Sub CheckResultType2()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Store marks for current student
        marks = Sheet1.Range("C" & i).Value
        
        If marks >= 75 Then
             Sheet1.Range("E" & i).Value = "Distinction"
        ElseIf marks >= 40 Then
             ' Write out names to to Column F
             Sheet1.Range("E" & i).Value = "Pass"
        Else
             Sheet1.Range("E" & i).Value = "Fail"
        End If
    
    Next

End Sub

Using nested IIfs we could do it like this:

' Description: Using a nested IIF function to check marks.
' Worksheet: Marks
' Output: Result are printed to the Immediate Windows(Ctrl + G)
' https://excelmacromastery.com/vba-if
Sub UsingNestedIIF()

    ' Get the data range
    Dim rg As Range
    Set rg = shMarks.Range("A1").CurrentRegion
    
    Dim i As Long, marks As Long, result As String
    ' Go through the marks columns
    For i = 2 To rg.Rows.Count
        
        marks = rg.Cells(i, 3).Value
        result = IIf(marks >= 55, "Credit", IIf(marks >= 40, "Pass", "Fail"))
        
        Debug.Print marks, result
    
    Next i

End Sub

Using nested IIf is fine in simple cases like this. The code is simple to read and therefore not likely to have errors.

What to Watch Out For

It is important to understand that the IIf function always evaluates both the True and False parts of the statement regardless of the condition.

In the following example we want to divide by marks when it does not equal zero. If it equals zero we want to return zero.

marks = 0
total = IIf(marks = 0, 0, 60 / marks)

However, when marks is zero the code will give a “Divide by zero” error. This is because it evaluates both the True and False statements. The False statement here i.e. (60 / Marks) evaluates to an error because marks is zero.

If we use a normal IF statement it will only run the appropriate line.

marks = 0
If marks = 0 Then
    'Only executes this line when marks is zero
    total = 0
Else
    'Only executes this line when marks is Not zero
    total = 60 / marks
End If

What this also means is that if you have Functions for True and False then both will be executed. So IIF will run both Functions even though it only uses one return value. For example

'Both Functions will be executed every time
total = IIf(marks = 0, Func1, Func2)

(Thanks to David for pointing out this behaviour in the comments)

If Versus IIf

So which is better?

You can see for this case that IIf is shorter to write and neater. However if the conditions get complicated you are better off using the normal If statement. A disadvantage of IIf is that it is not well known so other users may not understand it as well as code written with a normal if statement.

Also as we discussed in the last section IIF always evaluates the True and False parts so if you are dealing with a lot of data the IF statement would be faster.

My rule of thumb is to use IIf when it will be simple to read and doesn’t require function calls. For more complex cases use the normal If statement.

Using Select Case

The Select Case statement is an alternative way to write an If statment with lots of ElseIf’s. You will find this type of statement in most popular programming languages where it is called the Switch statement. For example Java, C#, C++ and Javascript all have a switch statement.

The format is

Select Case [variable]
    Case [condition 1]
    Case [condition 2]
    Case [condition n]
    Case Else
End Select

Let’s take our AddClass example from above and rewrite it using a Select Case statement.

' https://excelmacromastery.com/
Sub AddClass()
    
    ' get the last row
    Dim startRow As Long, lastRow As Long
    startRow = 2
    lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, Marks As Long
    Dim sClass As String

    ' Go through the marks columns
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Check marks and classify accordingly
        If Marks >= 85 Then
            sClass = "High Destinction"
        ElseIf Marks >= 75 Then
            sClass = "Destinction"
        ElseIf Marks >= 55 Then
            sClass = "Credit"
        ElseIf Marks >= 40 Then
            sClass = "Pass"
        Else
            ' For all other marks
            sClass = "Fail"
        End If
    
        ' Write out the class to column E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

The following is the same code using a Select Case statement. The main thing you will notice is that we use “Case 85 to 100” rather than “marks >=85 And marks <=100”.

' https://excelmacromastery.com/
Sub AddClassWithSelect()
    
    ' get the first and last row
    Dim firstRow As Long, lastRow As Long
    firstRow = 2
    lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, marks As Long
    Dim sClass As String

    ' Go through the marks columns
    For i = firstRow To lastRow
        marks = Sheet1.Range("C" & i).Value
        ' Check marks and classify accordingly
        Select Case marks
        Case 85 To 100
            sClass = "High Destinction"
        Case 75 To 84
            sClass = "Destinction"
        Case 55 To 74
            sClass = "Credit"
        Case 40 To 54
            sClass = "Pass"
        Case Else
            ' For all other marks
            sClass = "Fail"
        End Select
        ' Write out the class to column E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Using Case Is

You could rewrite the select statement in the same format as the original ElseIf. You can use Is with Case.

' https://excelmacromastery.com/
Select Case marks
    Case Is >= 85
         sClass = "High Destinction"
    Case Is >= 75
        sClass = "Destinction"
    Case Is >= 55
        sClass = "Credit"
    Case Is >= 40
        sClass = "Pass"
    Case Else
        ' For all other marks
        sClass = "Fail"
End Select

You can use Is to check for multiple values. In the following code we are checking if marks equals 5, 7 or 9.

' https://excelmacromastery.com/
Sub TestMultiValues()
    
    Dim marks As Long
    marks = 7
    
    Select Case marks
        Case Is = 5, 7, 9
            Debug.Print True
        Case Else
            Debug.Print False
    End Select
    
End Sub

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

These foods deeprootsmag.org viagra sildenafil help in excess stomach acid formation. This medicine will bring the happiness back and help sildenafil 100mg price men lead a healthy living that makes him feel pleasurable. Sexual buy tadalafil no prescription dysfunction is an obstinate physical or emotional issues linked with sex. SSL Protection Purchases online require the user giving out their personal information, address, etc. to the general public. viagra 100mg pills is known to be the most potent drug for ED How to get an ED pill? Is it available without prescription? The ED sufferers asked about these questions when planning to avail the treatment.

VBA: How to Test if a String starts with certain letters

There are many ways that we can test if the string which begin or start with the certain string or letter. Some time we want to perform the action only on certain field or records that begin or start with the specified letter. For example, we want to know how many customers have first name start with letter “P”. In this How To, I will show introduce the Like comparison operator, InStr, and Left built-in function.

Like comparison operator

We will use Like along with an asterisk (*) to test if the string begins with our substring.

Syntax

“String” Like “SubString*”  

Example of Like

Most of the time, we will use the If Statement to test if the string starts with the specified string. Per example of code below, we will get a message “Yep, this name begins with “Mo”” because the string is “Modesto” and the specified string “Mo*”.  The string “Mo*” means it begins with “Mo” and ignores the rest of the string.

If “Modesto” Like “Mo*” Then

    MsgBox “Yep, this name begins with ” & Chr(34) & “Mo” & Chr(34) & “”

End If

 Other than a hard code of string, it can be refer to the any field on current form or table. Per example below, the message “Yep, this name begins with “Mo”” because “Me.City” is referring to the current City field on current form which has a value as “Modesto.”

Private Sub cmdStartWith_Click()
If Me.City Like "Mo*" Then
    MsgBox "Yep, this city name begins with " & Chr(34) & "Mo" & Chr(34) & ""
   ‘or do something else
End If
End Sub

city-start-with-mo

Example of using Like in SQL for Subform

Like built-in function is widely used as a criteria for other functions. For example below, I use Like built-in function to find the category that begins with “t” that I type in the textbox. The result will display on the subform for category name that begin with t letter as shown below.

Private Sub cmdStartWith_Click()
Dim strSQL As String
Dim strLetter, StrCriteria As String
strLetter = Nz(Me.txtBeginWith, 0)
StrCriteria = "[category] like '" & strLetter & "*'"
    strSQL = "select * from category where " & StrCriteria
    Me.Category_DS.Form.RecordSource = strSQL
End Sub

subform-use-like

InStr built-in function

The InStr built-in function can be used to test if a String contains a substring. The InStr will either return the index of the first match, or 0.

Syntax

InStr ([start], string1, string2,[ compare ] )

start Is Optional. Numeric expression that sets the starting position for each search.
string1 Is Required. String expression being searched.
string2 Is Required. String expression sought.
compare Is Optional. Specifies the type of string comparison

Example:

IF Statement will be used to test if the return from InStr function is true. The InStr starts at the position 1 on string1 “Hello World” and looks for string2 “Hello W”. If InStr returns 1, it is true that the string1 (“Hello World,”) begins with the string2 (“Hello W”). A message will display “Yep, this string begins with Hello W!” as shown below. More information about InStr at MS website.

If InStr(1, “Hello World”, “Hello W”) = 1 Then

    MsgBox “Yep, this string begins with Hello W!”

End If

Another example, we can use only the String1 and String2, omit the Start and Compare. It is returning True same result as using Like comparison operator above.

If InStr(Me.City, "Mo") =1 Then
      MsgBox "Yep, this city name begins with " & Chr(34) & "Mo" & Chr(34) & ""
      ‘or do something else
End if

city-start-with-mo

Left built-in function

The Left built-in function is the most straight forward way to implement it in VBA.

Syntax

Left(Str, Length)

  • Str – is Required. String expression from which the leftmost characters are returned.
  • Length – is Required. Integer Numeric expression indicating how many characters to return from the left of string. If zero, a zero-length string (“”) is returned.

To determine the number of characters in Str, we will use the Len function. This example demonstrates the use of the Left function to return a substring of a given String. For example below, the given string is “Hello World!” and the number of characters to return from the left of the given string. The characters “He” will return from the Left function of the given string “Hello World!”

Dim TestString As String
TestString = "Hello World!"
  ' Returns "Hello".
  TestString = Left(TestString, 2)
  MsgBox "The 2 letters from the left of TestString = “ & teststring
End If

Create a Function from a Left built-in function

For the convenience of later use, we can create a function that will return True if the string begins with the certain string or character is true. We will use the Left built-in function as a part of function. We will call this function StartsWith() and place  it under the Module so we call it anywhere in this program.

Public Function StartsWith(strText As String, prefix As String) As Boolean   

StartsWith = Left(strText, Len(prefix)) = prefix

End Function

Call Function From Module on current record of form

Private Sub cmdStartWith_Click()
Dim strInv As String
strInv = "209"
   If StartsWith(Me.Customer_Phone, strInv) = True Then
       MsgBox "This customer has a phone number begins with " & Chr(34) & strInv & Chr(34) & ""         
       ‘or do something
   Else
       ‘or do something else
   End If
End Sub

phone-start-with-209

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

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

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

Structure of VBA If statements

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

Using a single line:

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

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

Multi-line syntax:

If condition [ Then ] 

[ statements_to_Execute ] 

[ ElseIf elseifcondition [ Then ] 

[ elseif_statements_to_execute ] ] 

[ Else 

[ else_statements_to_Execute] ] 

End If

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

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

First, a simple if statement example

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

Private Sub if_exmamples()

‘Single line if statement

numx = 15

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

End Sub

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

Using If with Else statement in a single line

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

Private Sub if_exmamples()

‘Single line if with Else Statement

numx = 20

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

End Sub

VBA if else

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

Using ElseIf statement with If..Else example

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Function ElseIf_exmample()

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

If btnVal = 6 Then

MsgBox «User pressed Yes!»

ElseIf btnVal = 7 Then

MsgBox «User Pressed No!»

Else

MsgBox «User Pressed Cancel!»

End If

End Function

VBA if ElseIf Else

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

Using If..ElseIf..Else with excel

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

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

The example code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

Private Sub dayName_Click()

Dim readValue As Integer

readValue = Range(«A1»).Value

If readValue = 0 Then

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

ElseIf readValue = 1 Then

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

ElseIf readValue = 2 Then

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

ElseIf readValue = 3 Then

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

ElseIf readValue = 4 Then

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

ElseIf readValue = 5 Then

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

Else

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

End If

End Sub

The result:

VBA if Excel

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Private Sub if_and_Click()

Dim color1 As String, color2 As String

color1 = Range(«A1»).Value

color2 = Range(«B1»).Value

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

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

Else

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

End If

End Sub

VBA if and Excel

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

if and false

An example of If..Else with Or operator

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Private Sub if_or_Click()

Dim color1 As String, color2 As String

color1 = Range(«A1»).Value

color2 = Range(«B1»).Value

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

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

Else

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

End If

End Sub

if or

An example of If with Not operator

See the use of Not operator in the example below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Private Sub if_not_Click()

Dim color1 As String

color1 = Range(«A1»).Value

If Not color1 = «Red» Then

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

Else

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

End If

End Sub

The result as I entered Yellow:

if not

As I entered the Red, the outcome:

if not false

This is because the if condition became false.

If 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

In this Article

  • VBA If Statement
    • If Then
  • ElseIF – Multiple Conditions
  • Else
  • If-Else
  • Nested IFs
  • IF – Or, And, Xor, Not
    • If Or
    • If And
    • If Xor
    • If Not
  • If Comparisons
    • If – Boolean Function
    • Comparing Text
    • VBA If Like
  • If Loops
  • If Else Examples
    • Check if Cell is Empty
    • Check if Cell Contains Specific Text
    • Check if cell contains text
    • If Goto
    • Delete Row if Cell is Blank
    • If MessageBox Yes / No
  • VBA If, ElseIf, Else in Access VBA

VBA If Statement

vba else if statement

If Then

VBA If Statements allow you to test if expressions are TRUE or FALSE, running different code based on the results.

Let’s look at a simple example:

If Range("a2").Value > 0 Then Range("b2").Value = "Positive"

This tests if the value in Range A2 is greater than 0. If so, setting Range B2 equal to “Positive”

vba if then

Note: When testing conditions we will use the =, >, <, <>, <=, >= comparison operators. We will discuss them in more detail later in the article.

Here is the syntax for a simple one-line If statement:

If [test_expression] then [action]

To make it easier to read, you can use a Line Continuation character (underscore) to expand the If Statements to two lines (as we did in the above picture):

If [test_expression] then _
    [action]
If Range("a2").Value > 0 Then _
   Range("b2").Value = "Positive"

End If

The above “single-line” if statement works well when you are testing one condition. But as your IF Statements become more complicated with multiple conditions, you will need to add an “End If” to the end of the if statement:

If Range("a2").Value > 0 Then
  Range("b2").Value = "Positive"
End If

vba end if

Here the syntax is:

If [test_expression] then
  [action]
End If

The End If signifies the end of the if statement.

Now let’s add in an ElseIF:

ElseIF – Multiple Conditions

The ElseIf is added to an existing If statement. ElseIf tests if a condition is met ONLY if the previous conditions have not been met.

In the previous example we tested if a cell value is positive. Now we will also test if the cell value is negative with an ElseIf:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
End If

vba elseif

You can use multiple ElseIfs to test for multiple conditions:

Sub If_Multiple_Conditions()

    If Range("a2").Value = "Cat" Then
        Range("b2").Value = "Meow"
    ElseIf Range("a2").Value = "Dog" Then
        Range("b2").Value = "Woof"
    ElseIf Range("a2").Value = "Duck" Then
        Range("b2").Value = "Quack"
    End If

End Sub

Now we will add an Else:

Else

The Else will run if no other previous conditions have been met.

We will finish our example by using an Else to indicate that if the cell value is not positive or negative, then it must be zero:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
Else
    Range("b2").Value = "Zero"
End If

vba else

If-Else

The most common type of If statement is a simple If-Else:

Sub If_Else()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        Range("b2").Value = "Not Positive"
    End If
End Sub

vba if else

Nested IFs

You can also “nest” if statements inside of each other.

Sub Nested_Ifs()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        If Range("a2").Value < 0 Then
            Range("b2").Value = "Negative"
        Else
            Range("b2").Value = "Zero"
        End If
    End If
End Sub

nested ifs

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

IF – Or, And, Xor, Not

Next we will discuss the logical operators: Or, And, Xor, Not.

If Or

The Or operator tests if at least one condition is met.

The following code will test if the value in Range A2 is less than 5,000 or greater than 10,000:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Then
    Range("b2").Value = "Out of Range"
End If

if or

You can include multiple Ors in one line:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Or Range("a2").Value = 9999 Then
    Range("b2").Value = "Out of Range"
End If

If you are going to use multiple Ors, it’s recommended to use a line continuation character to make your code easier to read:

If Range("a2").Value < 5000 Or _
   Range("a2").Value > 10000 Or _
   Range("a2").Value = 9999 Then

       Range("b2").Value = "Out of Range"
End If

vba multiple ors

If And

The And operator allows you to test if ALL conditions are met.

If Range("a2").Value >= 5000 And Range("a2").Value <= 10000 Then
    Range("b2").Value = "In Range"
End If

vba if and

VBA Programming | Code Generator does work for you!

If Xor

The Xor operator allows you to test if exactly one condition is met. If zero conditions are met Xor will return FALSE, If two or more conditions are met, Xor will also return false.

I’ve rarely seen Xor used in VBA programming.

If Not

The Not operator is used to convert FALSE to TRUE or TRUE To FALSE:

Sub IF_Not()
    MsgBox Not (True)
End Sub

vba if not

Notice that the Not operator requires parenthesis surrounding the expression to switch.

The Not operator can also be applied to If statements:

If Not (Range("a2").Value >= 5000 And Range("a2").Value <= 10000) Then
    Range("b2").Value = "Out of Range"
End If

if not

If Comparisons

When making comparisons, you will usually use one of the comparison operators:

Comparison Operator Explanation
= Equal to
<> Not Equal to
> Greater than
>= Greater than or Equal to
< Less than
<= Less than or Equal to

However, you can also use any expression or function that results in TRUE or FALSE

If – Boolean Function

When build expressions for If Statements, you can also use any function that generates TRUE or False.  VBA has a few of these functions:

Function Description
IsDate Returns TRUE if expression is a valid date
IsEmpty Check for blank cells or undefined variables
IsError Check for error values
IsNull Check for NULL Value
IsNumeric Check for numeric value

They can be called like this:

If IsEmpty(Range("A1").Value) Then MsgBox "Cell Empty"

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

If Application.WorksheetFunction.IsText(Range("a2").Value) Then _ 
   MsgBox "Cell is Text"

You can also create your own User Defined Functions (UDFs). Below we will create a simple Boolean function that returns TRUE. Then we will call that function in our If statement:

Sub If_Function()

If TrueFunction Then
    MsgBox "True"
End If

End Sub

Function TrueFunction() As Boolean
    TrueFunction = True
End Function

vba if boolean function

Comparing Text

You can also compare text similar to comparing numbers:

Msgbox "a" = "b"
Msgbox "a" = "a"

When comparing text, you must be mindful of the “Case” (upper or lower).  By default, VBA considers letters with different cases as non-matching.  In other words, “A” <> “a”.

If you’d like VBA to ignore case, you must add the Option Compare Text declaration to the top of your module:

Option Compare Text

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

Option Compare Text

Sub If_Text()
   MsgBox "a" = "A"
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA If Like

The VBA Like Operator allows you to make inexact comparisons of text. Click the “Like Operator” link to learn more, but we will show a basic example below:

Dim strName as String
strName = "Mr. Charles"

If strName Like "Mr*" Then
    MsgBox "True"
Else
    MsgBox "False"
End If

Here we’re using an asterisk “*” wildcard. The * stands for any number of any characters.  So the above If statement will return TRUE.  The Like operator is an extremely powerful, but often under-used tool for dealing with text.

If Loops

VBA Loops allow you to repeat actions. Combining IF-ELSEs with Loops is a great way to quickly process many calculations.

Continuing with our Positive / Negative example, we will add a For Each Loop to loop through a range of cells:

Sub If_Loop()
Dim Cell as Range

  For Each Cell In Range("A2:A6")
    If Cell.Value > 0 Then
      Cell.Offset(0, 1).Value = "Positive"
    ElseIf Cell.Value < 0 Then
      Cell.Offset(0, 1).Value = "Negative"
    Else
      Cell.Offset(0, 1).Value = "Zero"
     End If
  Next Cell

End Sub

vba else if statement

If Else Examples

Now we will go over some more specific examples.

Check if Cell is Empty

This code will check if a cell is empty. If it’s empty it will ignore the cell. If it’s not empty it will output the cell value to the cell to the right:

Sub If_Cell_Empty()

If Range("a2").Value <> "" Then
    Range("b2").Value = Range("a2").Value
End If

End Sub

vba if cell empty do nothing

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Check if Cell Contains Specific Text

The Instr Function tests if a string of text is found in another string. Use it with an If statement to check if a cell contains specific text:

If Instr(Range("A2").value,"text") > 0 Then
  Msgbox "Text Found"
End If

Check if cell contains text

This code will test if a cell is text:

Sub If_Cell_Is_Text()

If Application.WorksheetFunction.IsText(Range("a2").Value) Then
    MsgBox "Cell is Text"
End If

End Sub

If Goto

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

Sub IfGoTo ()

    If IsError(Cell.value) Then
        Goto Skip
    End If

    'Some Code

Skip:
End Sub

Delete Row if Cell is Blank

Using Ifs and loops you can test if a cell is blank and if so delete the entire row.

Sub DeleteRowIfCellBlank()

Dim Cell As Range

For Each Cell In Range("A2:A10")
    If Cell.Value = "" Then Cell.EntireRow.Delete
Next Cell

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

If MessageBox Yes / No

With VBA Message Boxes you’re able to ask the user to select from several options. The Yes/No Message Box asks the user to select Yes or No.  You can add a Yes / No Message Box to a procedure to ask the user if they would like to continue running the procedure or not. You handle the user’s input using an If statement.

Here is the Yes/No Message Box in practice:

vba yes no msgbox

Sub MsgBoxVariable()

Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

VBA If, ElseIf, Else in Access VBA

The If, ElseIf and Else functions work exactly the same in Access VBA as in Excel VBA.

You can use an If statement to check if there are records in a Recordset.

vba yes no msgbox

IF is one of the most popular and frequently used statements in VBA. IF statement in VBA is sometimes also called as IF THEN ELSE Statement. The task of the IF Statement is to check if a particular condition is met or not.

If you have followed my earlier posts, then you would remember that we discussed If Function in Excel. The IF Function in Excel and the IF Statement in VBA are basically designed to do the same tasks, but the way they work is slightly different from each other.

Excel IF function checks a particular condition and if the condition is TRUE, it returns one value otherwise it returns the second value.

On the other hand, VBA IF Statement checks a condition but it doesn’t return any value. If the condition evaluates to TRUE then, it simply takes the program control to the instructions inside the IF block and starts executing them sequentially. However, if the condition evaluates to FALSE then it takes the program control to the statements inside the Else Block.

VBA IF Statement

Although, it is not mandatory to have an Else Block with every IF statement. In such a case, if the condition inside IF statement evaluates to FALSE then the program control just moves to the next instruction (the instruction after the IF Block) and starts executing them sequentially.

Recommended Reading: Nested IF’s in Excel

Syntax of VBA IF Statement

Now let’s see the syntax of the IF statement in VBA:

IF condition_1 THEN
'Instructions inside First IF Block
ELSEIF condition_2 Then
'Instructions inside ELSEIF Block
...
ELSEIF condition_n Then
'Instructions inside nth ELSEIF Block
ELSE
'Instructions inside Else Block
END IF

Here, ‘condition_1’ to ‘condition_n’ refers to the expression that must evaluate to a Boolean value (i.e. either it should be TRUE or it should be FALSE).

The ‘THEN’ keyword is basically a directive signifying that the instructions immediately following the IF Statement are to be executed if the condition evaluates to TRUE.

IF function usually ends with an ‘END IF’ statement which tells the application that it is the last line of the IF function.

How VBA IF Statement Works

The conditions along with the IF Statements will be evaluated sequentially. This means, first of all, the IF Statement with ‘condition_1’ will be evaluated, if it evaluates to TRUE then statements inside the first IF block will be executed and the rest of the blocks (ELSEIF’s and ELSE blocks) will be skipped.

But, if the First IF Statement evaluates to FALSE then the ELSEIF statement following it will be evaluated. If it evaluates to TRUE then the instructions inside the ELSEIF Block will be sequentially executed and the rest of the blocks (ELSEIF’s and ELSE blocks) will be skipped.

However, in case, it also evaluates to FALSE then the next ELSEIF statement will be evaluated and so on. Finally, if all the IF and ELSEIF’s evaluate to FALSE then the ELSE block will be executed.

Note: Remember that out of IF, ELSEIF’s, and ELSE code blocks; only a single code block will be executed at a time based on the condition.

How to Use IF Statement in VBA

Now let’s understand how to use the IF Statement in VBA.

Before preceding let’s make our objective very clear.

Objective: Here we will generate a random number between 1-10 and then our task is to identify if the generated number is less than 5, equal to 5 or greater than 5.

So, we will try to write a VBA program as:

Sub IF_Test()
Dim num As Integer
num = WorksheetFunction.RandBetween(1, 10)
If num > 5 Then
MsgBox num & " is greater than 5"
ElseIf num = 5 Then
MsgBox num & " is equal to 5"
Else
MsgBox num & " is less than 5"
End If
End Sub

Explanation: In the above code we have used the RandBetween function of Excel to generate any random number from 1 – 10. After this, we have used an IF statement to check whether this number is greater than 5, equal to 5, or less than 5.

Based on the generated number, any one of the three conditions will evaluate to TRUE, and a suitable message box will pop out.

How this code works in three conditions:

If the Random number is greater than 5: Let’s consider the random number generated is 7. The program starts from Line-1 and executes all the instructions sequentially till Line-4. When it reaches Line-4 it checks ‘If 7  > 5’, which is TRUE. So, it jumps to the instruction immediately beneath it and pops up a message saying “7 is greater than 5”. After this, it directly jumps to the Line-10 and comes out of the whole IF Statement.

If the Random number is equal to 5: Let’s consider the random number generated is 5. In this case, when the program control reaches Line-4, it checks ‘If 5  > 5’, which is FALSE. So, it skips the IF Block and jumps to the ELSEIF statement, here it checks ‘If 5 = 5’ which evaluates to TRUE. So, it pops up a message saying “5 is equal to 5”. (I know it’s a weird message, but I just used it for helping you to understand the things.)

After this, the program control directly jumps to Line-10, skips the ELSE part, and comes out of the whole IF statement.

If the Random number is less than 5: Let’s consider the random number generated is 3. So, In this case, when the program control reaches Line-4 it checks ‘If 3 > 5’, which is FALSE. So, it skips the IF Block and jumps to the ELSEIF block, here it checks ‘If 3 = 5’, which also evaluates to FALSE.

Now, as the above two blocks have evaluated to FALSE hence the ELSE block will be executed and pops out a message saying “3 is less than 5”. Later the program control jumps to Line-10 and ends the IF Statement.

Examples of VBA IF Statement

Now, let’s move to some examples of the IF Statement in VBA.

Example 1: Using less than ‘<‘ operator with the VBA IF Function

Write a program to check whether the number entered by the user is negative or not.

Below VBA code can accomplish this:

Sub Find_Negative()
On Error GoTo catch_error
Dim number As Integer
number = InputBox("Enter the number: ")
If number < 0 Then
MsgBox "Entered number is negative!"
Else
MsgBox "Entered number is positive!"
End If
Exit Sub
catch_error:
MsgBox "Oops, Some Error Occurred !"
End Sub

Explanation:

In this code, first of all, we are accepting input numbers from the user. And then we check whether that number is greater than zero or not. If the number is less than zero, then IF block is executed and a message is displayed to the user saying, “Entered number is negative!”.

But however, if the entered number is greater than zero then the program jumps to the Else block where it displays a message to the user saying, “Entered number is positive!”.

Example 2: Using less than ‘=’ operator with the VBA IF Function

Write a VBA code to tell if the number entered by the user is Even or Odd.

Below is the code to do this:

Sub Find_Even_Odd()
On Error GoTo catch_error
Dim number As Integer
number = InputBox("Enter the number: ")
If number Mod 2 = 0 Then
MsgBox "Entered number is Even!"
Else
MsgBox "Entered number is Odd!"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub

Explanation:

In this code, just like the previous example first of all we are accepting input numbers from the user. And then we check whether the Modulus of that number with 2 is zero or not. If the Modulus is zero that means the number is divisible by 2 and hence is Even.

But however, if the modulus result is non-zero that means the number is not perfectly divisible by 2 and hence it is Odd.

Example 3: Using other functions within the VBA IF Function

Write a program to check if the string entered by the user is Palindrome or not.

A Palindrome string is that which reads the same forward as it does backward for example level, civic, etc.

Below is the code to accomplish this task:

Sub Check_Palindrome()
On Error GoTo catch_error
Dim word As String
Dim Rev_Word As String
word = InputBox("Enter the string ")
Rev_Word = StrReverse(word)
If LCase(word) = LCase(Rev_Word) Then
MsgBox "Entered String is Palindrome !"
Else
MsgBox "Entered String is non Palindrome !"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occured"
End Sub

Explanation:

The logic of this code is quite simple, first of all, we have asked the user to enter a text sting. And then with the use of VBA StrReverse a function (inbuilt function to reverse a text string), we have reversed the text string entered by the user.

Finally, we are matching both the strings i.e. user-entered string and reversed string in an IF statement to check whether both of them are the same or different. If both are the same that means the entered string is a palindrome.

Using IF statement with And & Or operators:

Logical operators make it possible for you to check multiple conditions at a time, inside a single IF statement. There are many logical operators in VBA like: And, Or, Not, AndAlso, OrElse, and Xor but in most cases, we only deal with the first three.

Note: All the above-mentioned operators are binary (i.e. they accept at least two operands) except NOT. NOT is unary because it takes a single operand.

Now, let’s have a look at their truth tables:

Condition NOT Result
True False
False True

After seeing the above truth table you can clearly see that Not just returns the opposite logic of the condition.

Condition1 Condition2 AND Result OR Result
True True True True
True False False True
False True False True
False False False False

See that AND only returns a TRUE value if both the conditions are TRUE. While OR returns TRUE if at-least any one of the two conditions is TRUE.

Now, let’s have a look at some examples of Logical Operators with IF Statement:

Example 4: Using OR Logical Operator With IF Statement in VBA

Write a program to ask the user his favorite color. If the color entered by the user is ‘White’ or ‘Black’, then display a message to tell him that you like the same color.

Below is the code to do this:

Sub Fav_Color()
On Error GoTo catch_error
Dim color As String
color = InputBox("Enter your favorite color: ")
If LCase(color) = "white" Or LCase(color) = "black" Then
MsgBox "Oh Really! I too like the same."
Else
MsgBox "Nice Choice"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub

See how I have used Or operator to check the combination of multiple conditions in my program.

Example 5: Using AND Logical Operator With IF Statement in VBA

In the below table we have a Grade Table. Our task is to write a program that accepts Marks from user and displays the corresponding Grade.

Grade Table Imgae 1

Below is the code to accomplish this:

Sub Grade_Marks()
On Error GoTo catch_error
Dim Marks As Integer
Marks = InputBox("Enter your marks: ")
If Marks <= 100 And Marks >= 85 Then
MsgBox "Grade A"
ElseIf Marks < 85 And Marks >= 75 Then
MsgBox "Grade B"
ElseIf Marks < 75 And Marks >= 65 Then
MsgBox "Grade C"
ElseIf Marks < 65 And Marks >= 55 Then
MsgBox "Grade D"
ElseIf Marks < 55 And Marks >= 45 Then
MsgBox "Grade E"
ElseIf Marks < 45 Then
MsgBox "Fail"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub

In this code see how I have used the AND operator to produce the required conditions.

Note: As a better coding practice it is always nice to use Select Case statements instead of writing multiple ELSEIF statements (just like we have seen in the above example). Select Case statements to execute faster and look cleaner than IF THEN ELSE.

Recommend Reading: Select Case Statement

So, this was all about VBA IF Statement. Do read this post if this long article has bored you and don’t forget to share your ideas and thoughts with us in the comments section.

Norie

Norie

Well-known Member

Joined
Apr 28, 2004
Messages
76,358
Office Version
  1. 365
Platform
  1. Windows


  • #2

Isaac

There isn’t a specific ‘string starts’ function, but there are plentyof other methods for checking strings.

Perhaps you could use this.

Code:

For Each ws In Worksheets
 
     If ws.Name Like "=>IT*" Or ws.Name Like "IT*" Then
        ws.Visible = xlHidden
    End If
 
Next ws

mvptomlinson

Well-known Member

Joined
Mar 10, 2008
Messages
2,638


  • #3

There is an InStr function which can check if one string exists within another, or you could use an If/Or, like

Code:

If Left(Sheets(1).Name,5) = "=> IT" Or Left(Sheets(1).Name, 2) = "IT" Then...

katzav

New Member

Joined
Oct 5, 2009
Messages
24


Понравилась статья? Поделить с друзьями:
  • Excel vba if sheet visible
  • Excel vba if shape selected
  • Excel vba if range then
  • Excel vba if not true
  • Excel vba if not text