VBA controlling code execution (2)
VBA's Select Case statement
The statement structure is contained within the Select Case...End Select key words. Highlighted lines 8 and 17 of the syntax window.
SYNTAX: Select Case statement
'' ======================================== '' Select Case statement '' '' Executes one of several groups of statements, depending on the value of an expression. '' '' Syntax '' '' Select Case testexpression '' [Case expressionlist-n '' [statements-n]] '' '' ... '' '' [Case Else '' [elsestatements]] '' '' End Select '' ========================================
Optional parameters or arguments are shown by the square brackets []
Using VBA Select Case statement
Using a sub procedure allows execution of the procedure with the F5 key. Output is sent to a Message Box
Code 1: Sub procedure SelectCaseTax
Sub SelectCaseTax()
Dim TaxInc As Long
Dim Tax As Double
TaxInc = 37001
Select Case TaxInc
Case Is <= 18200
Tax = TaxInc * 0
Case Is <= 37000
Tax = 0 + (TaxInc - 18200) * 0.19
Case Is <= 80000
Tax = 3572 + (TaxInc - 37000) * 0.325
Case Is <= 180000
Tax = 17547 + (TaxInc - 80000) * 0.37
Case Else
Tax = 54547 + (TaxInc - 180000) * 0.45
End Select
MsgBox "A Taxable Income of: " & Format(TaxInc, "Currency") & " incurs a tax liability of " & Format(Tax, "Currency")
End Sub
Code 1 by line number:
- Line 1: Procedure declaration: a
Subprocedure named SelectCaseTax. No arguments - the parentheses () are empty - Line 2: Declare a variable named TaxInc as type
Long - Line 3: Declare a variable named Tax as type
Double - Line 5: Assign the value 37,001 to the variable named TaxInc
- Line 8: The first logical test, will return false, execution skips to line 10
- Line 10: The second logical test, will return false, execution skips to line 12
- Line 12: The third logical test, will return true, execution continues at line 13
- Line 13: Assigns the value of
3572 + (37001 - 37000) * 0.325 = 3572.33to the Tax variable. The structure is complete, so the next line is line 18 - Line 18: The last line of the block
- Line 20: The MsgBox statement displays a message box in Excel. MsgBox uses the concatenation operator &, and the VBA Format function
- Related material: VBA controlling code execution (1) VBA If...Then...Else statement
- Acknowledgement: thanks to Krishna Triswara for providing corrections to this document
- This example was developed in Excel 2013 :: VBA 7.1
- Revised: Saturday 25th of February 2023 - 09:37 AM, [Australian Eastern Standard Time (EST)]
