3. Condition
Conditional Statements
Conditional statements are used to perform different actions for different decisions.
In Macros we have four conditional statements:
- If statement
- If...Then...Else statement
- If...Then...ElseIf statement
- Select Case statement
Here the samples you can refer:
If statement
Use the If...Then...Else statement if you want to
Range("L" & d).Select
If ActiveCell.Value = "" Then
r = counter - 1
formula = "=SUM(R[" & r & "]C:R[-1]C)"
ActiveCell.FormulaR1C1 = formula
Range("L" & counter).Select
Selection.NumberFormat = "#,##0.00"
Range("L" & counter).Select
Selection.Copy
Range("M" & counter).Select
ActiveSheet.Paste
Range("N" & counter).Select
ActiveSheet.Paste
Range("O" & counter).Select
ActiveSheet.Paste
Range("P" & counter).Select
ActiveSheet.Paste
Range("Q" & counter).Select
ActiveSheet.Paste
Range("R" & counter).Select
ActiveSheet.Paste
End If
If...Then...Else statement
If...Then...Else statement
If revenue > MCost Then
Range("L" & i).Select
ActiveCell.Value = revenue - MCost
Range("M" & i).Select
ActiveCell.Value = 0
Else
Range("L" & i).Select
ActiveCell.Value = 0 'Update Revenue column
Range("M" & i).Select
ActiveCell.Value = revenue - MCost * -1
End If
If...Then...ElseIf statement
If...Then...ElseIf statement
You can use the If...Then...ElseIf statement if you want to select one of many blocks of code to execute:
Range("C" & i).Select
If ActiveCell.Value <> "2002622" And ActiveCell.Value <> "2000461" Then
Rows(i & ":" & i).Select
Selection.Delete Shift:=xlUp
ElseIf ActiveCell.Value = "2000461" And STP = "" Then
Rows(i & ":" & i).Select
Selection.Delete Shift:=xlUp
End If
Select Case statement
You can also use the "Select Case" statement if you want to select one of many blocks of code to execute:
Range("J" & i).Select
Select Case ActiveCell.Value
Case "000010001200000001"
Range("L" & i).Select
If STP = "" And ActiveCell.Value <> 0 Then
Rows(i & ":" & i).Select
Selection.Delete Shift:=xlUp
End If
Case "000020000500000001"
Range("R" & i).Select
If STP = "" And ActiveCell.Value = 0 Then
Rows(i & ":" & i).Select
Selection.Delete Shift:=xlUp
Else
Range("L" & i).Select
revenue = ActiveCell.Value
Range("M" & i).Select
MCost = ActiveCell.Value
If revenue > MCost Then
Range("L" & i).Select
ActiveCell.Value = revenue - MCost 'Update Revenue column
Range("M" & i).Select
ActiveCell.Value = 0 'Update Material Cost column
Else
Range("L" & i).Select
ActiveCell.Value = 0 'Update Revenue column
Range("M" & i).Select
ActiveCell.Value = revenue - MCost * -1
End If
Range("R" & i).Select
ActiveCell.Value = revenue - MCost 'Update GP column
End If
Case "000020000200000001"
Range("C" & i).Select
If ActiveCell.Value <> "2002622" And ActiveCell.Value <> "2000461" Then
Rows(i & ":" & i).Select
Selection.Delete Shift:=xlUp
ElseIf ActiveCell.Value = "2000461" And STP = "" Then
Rows(i & ":" & i).Select
Selection.Delete Shift:=xlUp
End If
End Select
Comments
Post a Comment