12.9 If and Select Case
Priya needs an Excel label for each completed delivery. A ten-minute delivery earns Excellent, one above ten up to fifteen earns Good, and anything slower earns Late. A cancelled order or a missing time needs a different outcome. You will use an If block to choose a time label and Select Case to map city names to consistent codes.
Write the business decision in plain language
Ask whether a row can be classified first
HomeNest Supplies is a fictional seller preparing a report for a Blinkit-style delivery desk. The city codes and time thresholds in this exercise are example rules. The team looks at completed deliveries and wants a short label that matches agreed timing bands. A returned or cancelled row might still have a recorded time from an earlier step. The desk does not want it included as a completed delivery. A blank or textual number in a delivered row means the time cannot be used until the source is checked. These decisions come before the timing thresholds.
- Eligibility: Apply a delivery time band only when the status is Delivered. Cancelled, Returned and Pending are known states for this practice sheet and receive Timing not applicable. A new or missing status is a data quality issue and receives Review status.
- Measurement: Use a real numeric cell for elapsed minutes. A timing value must be zero or more in this lesson. The check treats zero as an explicitly recorded value. If your data uses zero to represent no measurement, use a different validation rule and state it plainly.
- Decision: For an eligible measurement, use Excellent from zero through ten, Good above ten through fifteen, and Late above fifteen. Record whether the boundary is included in the lower or upper band. An order at exactly fifteen belongs in Good under this rule.
- Output: Write a single label alongside that source row. It should be useful even when inputs are invalid. A review label lets the reader see that the current run did not accept the data; it replaces an earlier valid label for the practice row.
Trace the order of the tests
VBA's If Then Else block tests a condition. It executes that branch when the condition is true. ElseIf checks another condition only if the earlier one did not match. Else provides the final outcome when none of the stated conditions have matched. Use End If to finish a multi-line decision. Indent the body to keep the parts visible. Single-line If is useful for a very short rule, but a multi-branch classification is far easier to read as a block.
Suppose the first duration check is less than or equal to fifteen. It is true for nine, so the program can take that branch and give Good before it ever considers the ten-minute requirement. If the first check is less than or equal to ten, nine exits through Excellent, and eleven reaches the second check. The same comparisons, in a different order, produce different results. If a branch ends the decision, test which set of records is still available for the next branch.
Remember: Give each row a clear first matching rule. Check status and type first, then order overlapping thresholds from the specific band to the wider one.
Choose a decision pattern that matches the input
Use Select Case for one value compared against known choices
In a second exercise each city has a short code. The inputs are text labels such as Pune and Nashik. When you normalize the name, you can compare the same expression against a list of fixed strings. Choose Select Case to make those fixed branches easy to scan. Start with the normalized expression after Select Case. In separate Case blocks assign the corresponding result. Use Case Else for an unknown value, then close the structure with End Select.
- Match one exact choice: PUNE maps to PUN. The branch concerns the normalized value, so the original input can use a different case. It does not match a longer phrase containing the word Pune.
- Group multiple allowed choices: An example source may use the historical or current city label. The two allowed spellings SAMBHAJI NAGAR and AURANGABAD share the practice code SBN. This is a mapping used for the exercise. Use the approved naming conventions for a real organization.
- Handle other inputs: Case Else assigns UNK when the input did not match the list. That value calls for review. It does not silently map an unexpected location to a known city.
- Watch overlapping cases: A numeric Select Case can use a range such as Case 0 To 10 or a comparison such as Case Is <= 15. If multiple cases match the evaluated expression, the first one decides. Choose the ranges carefully and test values just below, on and just above their boundaries.
Combine conditions only when both sides are safe to evaluate
A condition can ask whether one thing and another thing are both true, or whether at least one of two conditions is true. In VBA, an And or Or expression should not be treated as a way to skip evaluation of its second part. A guard such as “the cell has a numeric value and the numeric conversion is greater than zero” can still try the conversion on invalid input. Use separate If or ElseIf stages when checking type before a comparison or conversion. Within the valid-status branch it is safe to compare the same checked string to several allowed words.
Lab one. Classify one delivered order across both boundaries
Give the source and label separate cells
Create BranchPractice.xlsm for this teaching example in approved desktop Excel. In that workbook add a sheet called Orders. Put one example order ID, BLK-1001, in A2. Enter the elapsed minutes in H2 and the status in I2. Use J2 as the only output cell for the timing label. A small marker in L2 should remain unchanged. In the first trial use the earlier course row with nine minutes and Delivered. Start from a visibly different old label so a new write will be easy to notice.
Option Explicit
Public Sub ClassifyDelivery()
Dim ws As Worksheet
Dim rawStatus As Variant, rawMinutes As Variant
Dim statusText As String, band As String
Set ws = ThisWorkbook.Worksheets("Orders")
rawStatus = ws.Range("I2").Value2
rawMinutes = ws.Range("H2").Value2
If VarType(rawStatus) = vbString Then
statusText = UCase$(Trim$(CStr(rawStatus)))
End If
If statusText = "CANCELLED" Or statusText = "RETURNED" Or statusText = "PENDING" Then
band = "Timing not applicable"
ElseIf statusText <> "DELIVERED" Then
band = "Review status"
ElseIf VarType(rawMinutes) <> vbDouble Then
band = "Review minutes"
ElseIf rawMinutes < 0 Then
band = "Review minutes"
ElseIf rawMinutes <= 10 Then
band = "Excellent"
ElseIf rawMinutes <= 15 Then
band = "Good"
Else
band = "Late - check with store"
End If
ws.Range("J2").Value2 = band
End Sub
- Read the status first. A Variant can hold a string, an empty cell or an error. Only the String branch produces a normalized status label. In a new call statusText starts empty. If the value is missing or invalid, that empty result leads to Review status.
- Decide whether the timer is relevant. The first three comparisons all compare the same checked string. They name three not-applicable statuses. Everything other than Delivered that did not match that list needs a review. The number tests apply only after the status tests have ruled out the other possibilities.
- Use the type checked in the previous step. Once a real duration is required, VarType distinguishes an ordinary numeric Value2 from text, errors and blanks. If the type guard fails, the later ElseIf clauses are skipped. A numeric zero is accepted, while a negative number is routed to Review minutes. The worksheet can physically store a numeric date serial, so this minimal fixture assumes known minute units.
- Write exactly one final label. The decision always puts one text value into band. After the block, the single J2 assignment stores that result. You can prove no previous label survived a newly invalid input by first running a valid row and then clearing its time.
| H2 minutes | I2 status | Expected J2 |
|---|---|---|
| 9 | Delivered | Excellent |
| 10 | Delivered | Excellent |
| 10.01 | Delivered | Good |
| 15 | Delivered | Good |
| 15.01 | Delivered | Late - check with store |
| 0 | Delivered | Excellent |
| Empty | Delivered | Review minutes |
| Text 10 | Delivered | Review minutes |
| -1 | Delivered | Review minutes |
| 11 | Cancelled | Timing not applicable |
| Empty | Returned | Timing not applicable |
| 11 | Unknown | Review status |
Verify an exact boundary and a rejected input
- Add the code to a standard module in the workbook's own project. Run ClassifyDelivery through Developer Macros. With nine and Delivered, J2 should show Excellent. A2 and L2 should remain as they were. The source values in H2 and I2 stay the same too.
- Try 10, then 10.01, then 15, then 15.01 under Delivered. After each edit run the macro, watch where the label changes and write down your result. Editing source cells alone does not recompute this macro's stored label. A new procedure run installs the latest outcome.
- With Delivered still set, clear H2 and run. The previous purpose of J2 was to show a label from the last run. This time expect Review minutes to replace it. Try a text-formatted 10 or an intentional division error in the practice cell and expect the same review outcome. Restore a numeric value when finished.
- Use the last three table examples to demonstrate that eligibility precedes timing. Cancelled with 11 is not eligible. Returned with no time belongs to the same group. Unknown status needs review regardless of the number beside it. Report these as distinct outcomes instead of treating every invalid row as late.
- Restore the original nine-minute delivered row. Verify that the label returns to Excellent and your note remains. If VBA cannot run under your environment, trace each of the test rows on paper and calculate what reaches the single final assignment. Leave the policy in place.
Trace the decision for a delivered row at 15.01 minutes
Check status
The normalized status is DELIVERED, so skip the return and status-review groups.
Check the measurement
15.01 is stored as a number and is nonnegative. Continue to the actual category rules.
Compare both cutoffs
It is above 10 and above 15, so neither of the first two speed conditions matches.
Write one label
The final Else supplies Late - check with store. Only J2 changes for this practice row.
Lab two. Match city labels with Select Case
Build one mapping a worksheet formula can call
In the same practice workbook, column C on Orders holds the city names. Use K as a separate formula column for corresponding codes. Start with Pune in C2 so K2 should show PUN, while the existing single timing exercise remains separate in J2. Add a few known and unknown labels below it. The function below returns a text code to the calling worksheet formula. It does not set the worksheet value by editing that cell from VBA.
Public Function CityCode(ByVal city As String) As String
Select Case UCase$(Trim$(city))
Case "PUNE"
CityCode = "PUN"
Case "NASHIK"
CityCode = "NSK"
Case "NAGPUR"
CityCode = "NGP"
Case "KOLHAPUR"
CityCode = "KOP"
Case "SOLAPUR"
CityCode = "SLP"
Case "SAMBHAJI NAGAR", "AURANGABAD"
CityCode = "SBN"
Case Else
CityCode = "UNK"
End Select
End Function
Check known, alias and unknown cases
- Add CityCode below the Sub in the same standard module. Keep just one Option Explicit at the beginning of the module. Save as XLSM. Check that the formula input cells contain text labels. If the host is not allowed to evaluate the VBA function, trace the cases manually.
- Enter the formula below in K2. Read the code PUN. Fill the formula down relative to the C cells containing other test labels. The function returns to each worksheet cell independently when recalculated, so C3 can lead to a different code in K3.
- Try the two accepted names Sambhaji Nagar and Aurangabad on two different rows. They give SBN. Try lower-case nashik with ordinary outside spaces. The function removes those spaces and compares uppercase text, producing NSK. The dashboard uses a short code to group those records.
- Enter a city with an unrecognized spelling, such as Mumbai for this dataset. Expect UNK. Use the explicit empty text example below to check the fallback. A worksheet error value is different from ordinary text and is outside this function's String input assumption. For a real report, inspect source errors separately rather than assuming an error is an eligible location.
- In your lab copy, change a known city row from Pune to Nagpur. With ordinary automatic calculation its K formula should now return NGP. No button run is needed for that row's formula. Verify that J2 currently shows what the Sub last wrote, illustrating one procedure that stores a result and one function that provides a calculated value.
K2: =CityCode(C2)
=CityCode("")
| Input city | Code | Reason |
|---|---|---|
| Pune | PUN | Known Pune branch |
| nashik with outside spaces | NSK | Trim and normalize case |
| Nagpur | NGP | Known Nagpur branch |
| Kolhapur | KOP | Known Kolhapur branch |
| Solapur | SLP | Known Solapur branch |
| Sambhaji Nagar | SBN | Known city label |
| Aurangabad | SBN | Accepted alternate label |
| Mumbai | UNK | Outside the practice map |
| Empty text | UNK | No known city match |
Say what normalization can and cannot repair
Trimming ordinary spaces at either end and converting text to uppercase are two deliberate transformations. A double space between words, a nonbreaking space from a copied web page or a different spelling in the middle remains distinct under this tiny procedure. If your source has those forms, confirm which ones are valid with the owner of the city lookup. A controlled mapping table may be easier to maintain if there are many values and aliases. An unknown result is useful as a review queue rather than a reason to pick whichever city looks similar.
Diagnose a late label using the rule order
Clarify what first match means
Suppose another analyst writes separate If blocks, one for less than or equal to ten and a second for less than or equal to fifteen, assigning the same destination after each match. With nine, both can run. The second assignment could overwrite Excellent with Good. One If with ElseIf builds an exclusive set of choices in order. After the first applicable rule the other branches are skipped. Think about whether your cases are supposed to be exclusive or whether the action genuinely needs several independent checks.
For the three timing thresholds, a checked numeric value could also be classified with Select Case. A clear version puts the first comparison at less than or equal to ten, then the next comparison at less than or equal to fifteen, then Case Else. The comparison expression is evaluated once for the Select Case statement, and the first matching branch determines the outcome. These shorthand conditions assume the earlier validation already removed negatives. For a new rule that uses two variables, If with readable Boolean tests may be easier to follow.
Select Case checkedMinutes
Case Is <= 10
band = "Excellent"
Case Is <= 15
band = "Good"
Case Else
band = "Late - check with store"
End Select
The snippet demonstrates only the final bands with a previously assigned checkedMinutes. It is not a standalone procedure. The main practice macro first handles status, number and sign. If somebody rewrites its whole decision using only the snippet, a cancelled row with a recorded nine minutes could be called Excellent. Keep eligibility as a test of its own. A new code shape should preserve the original business rule unless the report owner changes it.
Study the gap between a comparison and a display
A duration of 10.01 can appear as 10 when the cell shows no decimal places. The If block reads the underlying number, so the result is Good. A coworker looking only at the styled cell might expect Excellent. Read the formula bar or add decimals before assuming a logic problem. If the report should classify according to an officially rounded measure, build that rounding into the stated rule and update the boundary tests.
Discuss how the rule should handle time units. The simple data contains elapsed minutes such as 10 and 15. A worksheet may also represent a duration as part of a day. Ten minutes in that representation is less than one, so comparing it directly to 10 would be a unit mistake even though the type is numeric. Determine whether the source contains elapsed minutes or an Excel time value before applying band logic. Multiplying a day fraction by 24 hours and 60 minutes converts it to minutes. Verify with one known duration after conversion, then compare the bands.
Apply the same rules to ten known orders
Make the given source data an independent check
The lesson dataset provides ten order records with a status and elapsed minutes. Before writing a new routine to cover a complete sheet, predict each decision on paper. Use the same eligibility rule from the small macro. A comment such as “treat shipped lines as completed” is too vague when some statuses have special meanings. Decide which exact labels count as delivered and check the result list before aggregating it.
| Outcome | Order IDs | Count |
|---|---|---|
| Excellent | BLK-1001, BLK-1006 | 2 |
| Good | BLK-1002, AMN-1003 | 2 |
| Late | AMN-1005, BLK-1007, BLK-1010 | 3 |
| Timing not applicable | BLK-1004, AMN-1008, BLK-1009 | 3 |
There are seven eligible orders and three others. The ten rows all have a stated classification even though the workflow deliberately excludes three based on status. Check the seven delivered records separately. Minutes 9 and 8 qualify for Excellent, 12 and 14 for Good, and 16, 18 and 17 for Late. These references point back to the original IDs. Changing the rule to include every measured row would bring in cancelled and returned examples and alter the group count. That is a change in the source definition.
Use changed inputs to detect mistaken rules
- Prove the lower boundary still belongs to the first band. Consider replacing an eligible nine with ten. It should remain Excellent. Changing that value to ten plus one hundredth moves it to Good. If both runs report Good, check the order or inclusiveness of the first two conditions.
- Prove the upper boundary belongs to the middle band. An eligible order at 15 should remain Good. An order at 15.01 should move to Late. A branch coded with strictly less than fifteen would move the exact boundary into the slow group too early.
- Prove cancelled status has priority over speed. AMN-1008 has a recorded ten minutes but is Returned. Applying the duration rule first could give Excellent. Applying the agreed eligibility check first gives Timing not applicable. These outcomes answer different reporting questions. Record which one the current team asked for.
- Prove an incomplete row calls for review. Pick the delivered AMN-1003 with fourteen minutes. Imagine its elapsed field is temporarily unavailable. The result should change from Good to Review minutes after the macro is run for that row. It should not drift toward Excellent or stay Good because the earlier output was not replaced.
Decide how to share a classification rule
A daily sheet can use a saved label when a reviewer needs the original decision left in place after the run. A live worksheet formula can calculate its labels when raw minutes are updated. If other work depends on how many orders are Late right now, a live formula or a deliberate rerun is necessary. In this exercise the macro writes a stored text label while the city function produces a recalculated result. A complete report should indicate the run state or underlying data date so the reader knows which labels are current.
Say the rule is changed next week so the Good band ends at fourteen. Values from just above fourteen through fifteen move to Late. On the ten-order practice data, the original two Good records have duration twelve and fourteen and remain Good. That dataset alone would fail to reveal the boundary change. Your 15 and 15.01 edge fixture shows exactly where the new behavior differs. Always keep an edge test outside the current data when a cutoff matters.
Read a mistaken branch as a clear support problem
Compare symptoms without rewriting the working path
- Unknown code for a familiar word: Inspect the actual input. The city function removes ordinary outside spaces and converts case. A second internal space or punctuation changes the normalized key. If the intended city label and full spelling are valid, update the explicit mapping with the approved form and test the returned code.
- Whole numbers pass while decimal values land in a gap: A Case rule starting the Good band at eleven would skip values such as 10.01 if the input can have decimals. Our ordered comparisons cover the full nonnegative range. Write down the domain of allowed values and choose comparisons that fit it.
- Outcome present even though a source amount is invalid: Check whether the saved result belongs to a previous run. In this exercise rerunning after an invalid entry writes a review label. A worksheet formula recalculates from its own source cells. They require different evidence to determine freshness.
- Exception in an invalid data case: Review conditions that perform a conversion and a type test in the same Boolean expression. Type checks and conversions belong in separate ordered stages when one could fail for a value rejected by the other. The guarded ElseIf sequence handles a formula error or text duration without trying to compare it to ten.
- Upper rules swallow lower rules: Check which condition comes first and whether a selected branch ends the structure. One ElseIf chain has a first applicable path, so any wider early threshold can hide narrower rules later. Independent If blocks can instead do multiple writes if their criteria overlap.
Trace one unexpected row: Make a note with the source status, raw duration type, numeric value if usable, first matching branch and exact output cell. Compare your note with a partner's rather than looking only at whether both display the word Good.
Choose whether a row can have more than one outcome
Compare a single band with several independent observations
One timing band belongs in J2. An eligible row should not have both Good and Late. The code achieves this by assigning a text value in one mutually exclusive branch and writing it once afterward. But a review desk may ask two independent questions: did the order exceed the promised time, and is the value at least two hundred rupees? A row may meet both conditions. In that case a single ElseIf chain would hide whichever observation occurs second. Put the two answers in separate outputs and test their meanings independently.
Consider AMN-1005 from the original order list. Its duration is sixteen minutes, its status is Delivered and its amount is 232. The timing exercise gives it Late. With an illustrative internal amount check of at least 200, it also meets that condition. BLK-1010 lasts seventeen minutes and is Delivered, but its amount is 90, so it reaches the Late band but not the amount threshold. AMN-1003 lasts fourteen minutes, has 110 and is Delivered. It gets Good and does not meet the amount threshold. These are independent observations, so preserving both numbers and their labels serves a different purpose from assigning a single status.
A cancelled row can also meet an amount condition even though its timing is ineligible. BLK-1009 has 220, but its status is Cancelled. Whether the amount flag should apply to cancelled entries is part of that second rule and must be stated separately. If the analyst intends to flag delivered revenue only, the amount rule needs an explicit delivered check. Set the condition from the business meaning and cover an example where the source number fits but the status does not. The quick test can be done on paper without changing the current J2 exercise.
Make a review queue you can explain
Suppose the daily worksheet summary uses three counters called Timed, Other known statuses and Review. Seven original records count as Timed. Three count under other known statuses. Zero need a review under these small practice rules. If you clear the minutes for one delivered row and apply the same rule set, Timed becomes six, Other remains three and Review becomes one. The total still adds to ten. This is an independent coverage check: one row moved categories and no records disappeared. You can use the IDs to locate the exact row once a count changes.
Now consider a missing status in a row that already has a valid duration. The row moves to Review status even though the numeric type is valid. It should be obvious in your run notes which field requires attention. If the worksheet output just said “bad,” a supervisor would have to search both fields. Explicit review labels give a precise starting point. Add the actual input ID beside any handoff and state which check classified it, so the person resolving the issue does not guess from a formatted cell.
Test a new alias without disturbing existing matches
Before adding a new allowed value to CityCode, write down the expected result for the approved new label, an existing alias and an unrelated unknown label. If someone wants “Nashik City” to use the same practice code as Nashik, add that exact approved value to the matching Case branch in your copy. Then test NSK for both forms, SBN for Aurangabad and UNK for “Nashik Village” unless it too was specifically approved. A broad substring match could choose the same code for both without authorization from the data owner. This small set of tests helps you distinguish desired normalization from unintended expansion of the mapping.
Keep the old results recorded before changing the practice function. Changing only the mapping should leave the timing macro unaffected, because it uses its own fields and assignment. Check one unchanged timed delivery at the end, such as Delivered at nine. That gives you one check for the change you wanted and one check that the operation outside it still follows its previous rule. If the new mapping later needs removal, keep the partner test with the exact old and new label. It lets you restore the intended behavior without changing the branches that still serve other cities.
Quick checks
Trace the first matching rule
What is the result for Delivered at exactly ten minutes?
Excellent. The status and numeric value are valid, so the first time cutoff applies. The inclusive comparison accepts ten. If you entered 10.01 the same type checks pass but the first band does not. The second cutoff then gives Good.
What is the result for Returned with nine minutes?
Timing not applicable. The status branch applies before the timer is classified. Although nine would fit the Excellent band for a delivered row, the workbook question uses time categories only for completed deliveries. Keep the three non-delivered practice statuses separate from unknown source values.
How does the procedure handle text containing the characters 10?
The text stored in the Value2 result is a String. This exercise expects a numeric cell, so it writes Review minutes. A readable input can still be in an unsupported type. Confirm source typing and units before converting the cell to valid numeric data.
Why put the less-than-or-equal-to-ten check before the less-than-or-equal-to-fifteen check?
A number no greater than ten also satisfies the wider comparison. The first true branch of an ElseIf block decides the classification. Checking fifteen first would label nine Good. The order shown lets numbers above ten reach the second band and gives exactly fifteen to Good.
Which label is expected for an unfamiliar city input?
CityCode finishes with Case Else and assigns UNK when no mapped value matches. A review report can list unknown values for the owner to check. The function does not assume that an unfamiliar value belongs to the nearest-looking city code.
How many of the ten original orders have a usable delivered timing label?
Seven are Delivered. Two are Excellent, two are Good and three are Late. The two Cancelled rows and the one Returned row receive Timing not applicable. Compare group counts and sample source IDs so you can see whether a classification accidentally included other statuses.
Interview and discussion
Explain the contract before showing the code
When is Select Case a good choice?
It is useful when you compare one known expression against a set of branches. Here one normalized city name can match an exact string or a group of approved strings. The first matching branch decides and Case Else handles the unknown input. An If block can be clearer when the decision depends on multiple values or earlier validations.
How would you test that a cutoff is applied correctly?
Write comparable valid inputs just below, on and just above the cutoff. For ten, choose 9.99, 10 and 10.01 while status remains Delivered. Predict the exact First band, First band and Second band outcomes before running. Then add an irrelevant or invalid status to demonstrate the separate eligibility rule.
When should an input not reach a comparison?
Check that the field contains a valid value before comparing or converting it. A formula error, missing time or text field needs its own route. Ordered ElseIf blocks let the type check take its own branch. A combined VBA And test does not provide a reliable shortcut around the right-side conversion.
Why is the status Not applicable different from Review status?
In this practice rule the known Cancelled, Returned and Pending categories intentionally do not get a delivery time classification. An unknown or missing value needs a person to inspect the source because its eligibility is uncertain. Naming those outcomes separately helps downstream users distinguish excluded rows from data quality problems.
How do your checks change when you use a worksheet function instead of a stored tag?
For the macro, rerun the procedure after changing the source and read the stored label in J2. For the city function, observe the value calculated by the formula in its own cell after a source edit. Always trace both results to the exact workbook input and the point when each is refreshed.
Six recall cards
- Check eligibility
Only Delivered status can enter the timed branches. A known incomplete status and an unknown status have different labels.
- Check the value
Read the actual numeric minutes and check sign before choosing a band. A blank or textual number earns Review minutes.
- First match wins
Place the ten-minute condition before the fifteen-minute condition. Test below, equal and above both boundaries.
- Match one expression
Use Select Case for a normalized city key. Two approved spellings can share one Case result.
- Make the fallback explicit
Use Else or Case Else so a valid but unexpected input reaches a stated review outcome.
- Label freshness
The macro stores a label from the last run. The city formula returns a value from current inputs when calculated.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.