Select Case Tutorial
Get your Select Case statement running in minutes. Give us a call and we will solve the problem or there is no charge!
410-708-1417
VBA Select Case statement is one of the most useful Access VB tools used to program MS Access forms and reports.The select case visual basic command takes the place of multiple nested if statements and makes your VB code clean and much easier to follow by neatly handling the conditional flow of your VBA programming code.The syntax of the Access Case statement is:Select Case Expression
Case Expression_1
Statement_1
Case Expression_2
Statement_2
Case Expression_n
Statement_n
…
End Select
Where Expression is a variable passed to the subroutine or a field on a form or within a recordset.
And Expression_1 to n are either constants, ranges of values, series of values, or calculations which resolve to a value for each Case. You can also use alphanumeric comparisons in both the main Expression and the conditional Expressions (1..n).
In the VBA Select Case statement example below we have a report parameter form that has three choices for report output options:
1 – Label report
2 – Datasheet view of query results
3 – A series of statements to prepare an address file
Here is the example Access Case statement used in visual basic code:
Private Sub Command5_Click()
Dim pitney As String
Dim sqltext As String
Dim rst As DAO.Recordset
Dim db As DAO.Database
Dim stDocName As String
On Error GoTo Err_Command5_Click
Select Case Me.Output_Options
Case 1
stDocName = “R_Daily_Prospect_Labels”
DoCmd.OpenReport stDocName, acPreview
Case 2
DoCmd.OpenQuery “Q_Daily_Prospect_Labels”
Case 3
Set db = CurrentDb
pitney = DLookup(“Path”, “Q_path_Pitney”, 1 = 1)
pitney = Replace(pitney, “/”, “”)
pitney = Replace(pitney & “”, “\”, “”)
pitney = pitney & “pitneybowes.mdb”
DoCmd.RunSQL “delete * from mailmerge in ‘” & pitney & “‘”
sqltext = “INSERT INTO mailmerge (name,address1,address2,city,state,zip) in ‘” & pitney & “‘” & _
” select name,address1,address2,city,state,zip from q_daily_prospect_Pitney”
DoCmd.RunSQL (sqltext)
Set rst = db.OpenRecordset(“select count(name) as icount from mailmerge in ‘” & pitney & “‘”)
rst.MoveFirst
MsgBox “A total of ” & Nz(rst!Icount, 0) & ” records were inserted into ” & pitney
rst.Close
Set rst = Nothing
End Select Call Mark_As_Sent_Click
Exit_Command5_Click:
Exit Sub
Err_Command5_Click:
MsgBox Err.Description
Resume Exit_Command5_Click
End Sub
More Information and Example for the VBA Select Case Statement:
VBA Select Case in Proper Case Letters
Access Case Statement in Form Field Validation
Microsoft Office VBA, MS Access 2003, 2007, 2010, 2013, 2016