Excel VBA Conditional Statement
Conditional Statement in VBA Excel
Conditional Statements in Excel VBA are one of the most powerful and useful features in programming, this will give you to perform comparisons to decide or loop through a specified number of iterations based on certain criteria.
The various conditional statements are as follows:
- IF….THEN statement
- IF…..THEN …ELSE Statement
- If … ElseIf … Else Statement
- If … ElseIf … ElseIf Statement or Nested If statement
- Select … Case
Example 1
Sub Conditional_Statement_Example1() Dim CurRow As Byte CurRow = 2 'Using Do Until Loop Do Until Cells(CurRow, 1) = "" 'If..Else statement If Cells(CurRow, 3) > 200 Then Cells(CurRow, 5) = "Qualified" Else Cells(CurRow, 5) = "Not Qualified" 'Closing the IF End If CurRow = CurRow + 1 Loop End Sub
Output
Example 2
Sub Conditional_Statement_Example2() 'Variable declaration Dim Marks As String 'Accepting the month by the user Marks = InputBox("Enter the students percentile marks:", "Marks") If Marks <= 100 And Marks >= 91 Then 'Check if the Student's Grade is A1 MsgBox "Grade : A1" ElseIf Marks < 91 And Marks >= 81 Then 'Check if the Student's Grade is A2 MsgBox "Grade : A2" ElseIf Marks < 81 And Marks >= 71 Then 'Check if the Student's Grade is B1 MsgBox "Grade : B1" ElseIf Marks < 71 And Marks >= 61 Then 'Check if the Student's Grade is B2 MsgBox "Grade : B2" ElseIf Marks < 61 And Marks >= 51 Then 'Check if the Student's Grade is C1 MsgBox "Grade : C1" ElseIf Marks < 51 And Marks >= 41 Then 'Check if the Student's Grade is C2 MsgBox "Grade : C2" ElseIf Marks < 40 And Marks >= 33 Then 'Check if the Student's Grade is D MsgBox "Grade : D" Else 'Check if the student has failed MsgBox "Grade : Fail" End If End Sub
Output
Example 3
Sub Conditional_Statement_Example3() Select Case Range("B2") Case "C2" Range("C2") = Range("B2") / 100 Case "D2" Range("D2") = Range("B2") / 100 Case "D3", "D4" Range("E2") = Range("B2") / 100 Case Else Range("F2") = Range("B2") / 100 End Select End Sub
Output