Sub topic 6
Writing Threshold Logic with VAR and SWITCH(TRUE())
This chapter assumes you can build a table or matrix in Power BI Desktop, write basic measures with SUM and DIVIDE, and use the Format pane. It also assumes you know how to apply "Format by field value" to a visual, which an earlier chapter covered. Here the focus is the DAX that decides which color a cell gets.
Why threshold logic needs structure
A color measure answers one question for every cell: which band does this value fall into? A variance of 7% might be green, 2% amber, and -3% red. The logic is a ladder of tests, where the first test that passes decides the result.
You can write that ladder with nested IF functions. It works, but it gets hard to read after two or three levels. DAX offers a cleaner pattern that combines two features:
- VAR, which stores a value once so you can name it and reuse it.
- SWITCH(TRUE(), ...), which reads like a list of conditions with a result for each.
Variables with VAR and RETURN
A variable is a named value that DAX calculates once inside a measure. You declare it with VAR and finish the measure with RETURN, which gives the final result.
Variance Color Simple =
VAR v = [Variance %]
RETURN
IF ( v >= 0, "#2E7D32", "#C62828" )Variables help in three ways:
- Readability. The name
vstands for a longer expression, so the test is short. - Speed. The base measure is evaluated once, not once per test. If
[Variance %]appeared in three tests without a variable, DAX could evaluate it three times. - Consistency. Every test sees the same number.
A variable is evaluated in the filter context where it is declared. Inside a visual, that means the row or column the cell belongs to. Later changes to the context inside RETURN do not affect it.
The measures in this chapter build on these base measures:
Total Sales = SUM ( Sales[Amount] )
Sales Target = SUM ( Targets[TargetAmount] )
Variance % =
DIVIDE ( [Total Sales] - [Sales Target], [Sales Target] )DIVIDE returns blank, not an error, when the target is zero or missing. That matters for the blank test later in this chapter.
How SWITCH(TRUE()) works
SWITCH normally compares one expression against a list of values:
SWITCH ( Product[Category], "Bikes", 1, "Parts", 2, 0 )That form can only test equality. Thresholds need comparisons such as "greater than or equal to". The trick is to pass TRUE() as the first argument. SWITCH then walks the list from top to bottom and returns the result paired with the first condition that evaluates to TRUE.
Variance Color =
VAR v = [Variance %]
RETURN
SWITCH (
TRUE (),
ISBLANK ( v ), BLANK (),
v >= 0.05, "#2E7D32",
v >= 0, "#F9A825",
"#C62828"
)Read it as a sentence: if the variance is blank, return no color. Otherwise, if it is at least 5% above target, return green. Otherwise, if it is at or above target, return amber. Otherwise, return red.
The last argument has no condition. It is the default, used when no test passes.
Order matters
SWITCH(TRUE()) stops at the first true condition. This makes the order of your tests part of the logic.
Consider what happens if you reverse the green and amber tests:
Variance Color Wrong Order =
VAR v = [Variance %]
RETURN
SWITCH (
TRUE (),
v >= 0, "#F9A825",
v >= 0.05, "#2E7D32",
"#C62828"
)A variance of 8% passes v >= 0 first, so it returns amber. The green test is never reached. The rule is to put the most restrictive test first and work toward the most general one.
For a "higher is better" measure, list the highest threshold first. For a "lower is better" measure such as defect rate or late deliveries, flip the direction and list the lowest threshold first.
Defect Color =
VAR rate = [Defect Rate]
RETURN
SWITCH (
TRUE (),
ISBLANK ( rate ), BLANK (),
rate <= 0.01, "#2E7D32",
rate <= 0.03, "#F9A825",
"#C62828"
)The blank trap
In DAX, a blank compared with a number behaves like zero in many comparisons. A blank v passes v >= 0, so a cell with no data would be colored amber. That is misleading: amber says "on target" for a cell where nothing was measured.
This is why the blank test sits first in Variance Color. Putting ISBLANK ( v ) at the top catches the missing value before any numeric test runs. Later chapters cover blanks and totals in more depth, but the placement rule belongs here: guard conditions go first.
Choosing the result type
Every result in a SWITCH should be the same kind of value. For Format by field value, the measure must return text that Power BI can read as a color. Hex strings such as "#2E7D32" are the most reliable. Mixing text and numbers in one SWITCH can cause errors or unexpected conversions, and returning BLANK() alongside strings is fine because blank means "apply no color".
Keep the hex codes consistent across your reports. A good habit is to store each color in a small measure and reference it:
Color Good = "#2E7D32"
Color Warn = "#F9A825"
Color Bad = "#C62828"
Variance Color (Named) =
VAR v = [Variance %]
RETURN
SWITCH (
TRUE (),
ISBLANK ( v ), BLANK (),
v >= 0.05, [Color Good],
v >= 0, [Color Warn],
[Color Bad]
)Changing the palette now means editing three measures, not every color measure in the model.
Testing the logic
Before you attach a measure to a visual, check its output. Add the measure to a table visual next to [Variance %]. You should see hex strings in the measure column. For each band, find a row that belongs in it and confirm the string matches.
Pay attention to the boundaries. A variance of exactly 0.05 should be green under v >= 0.05. A variance of exactly 0 should be amber. Floating-point results from division can land at 0.04999999, so if a boundary case matters, test with real data and consider rounding:
Variance Color (Rounded) =
VAR v = ROUND ( [Variance %], 4 )
RETURN
SWITCH (
TRUE (),
ISBLANK ( v ), BLANK (),
v >= 0.05, "#2E7D32",
v >= 0, "#F9A825",
"#C62828"
)ROUND leaves a blank as blank, so the blank guard still works.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Tests in the wrong order | Good values show the middle color | Put the strictest test first |
| No blank guard | Empty cells show amber or green | Add `ISBLANK ( v )` as the first test |
| Missing default result | Unmatched values return blank and get no color | Add a final result with no condition |
| Comparing the measure repeatedly instead of using a variable | Slow visuals on large models | Store it in a VAR |
| Using `=` for ranges | Only exact values match | Use `>=` and `<=` with `TRUE()` |
| Hex code without `#` or with a typo | Format does not appear | Check the string in a table visual |
Nested IF compared with SWITCH(TRUE())
The two forms give the same result. This is the same logic as nested IF:
Variance Color (IF) =
VAR v = [Variance %]
RETURN
IF (
ISBLANK ( v ), BLANK (),
IF (
v >= 0.05, "#2E7D32",
IF ( v >= 0, "#F9A825", "#C62828" )
)
)With three bands the difference is small. With six bands, SWITCH(TRUE()) stays a flat list while nested IF grows deeper with each band. Flat lists are easier to review and edit, so prefer SWITCH(TRUE()) for any measure with more than two outcomes.
Exercises
Exercise
A measure uses SWITCH(TRUE()) with the tests v >= 0 returning amber, then v >= 0.05 returning green, then a default of red. A cell has a variance of 12%. Which color does it receive, and how do you fix the measure?
Show answer
It receives amber. SWITCH stops at the first true test, and 12% satisfies v >= 0 before the green test is reached. Fix it by putting v >= 0.05 before v >= 0, so the strictest test comes first.
Exercise
You write a color measure with the tests v >= 0.05, v >= 0, and a red default, and no blank test. A product has no sales and no target, so [Variance %] is blank. What color might the cell get, and what do you add to prevent it?
Show answer
The blank can pass v >= 0 because a blank compares like zero in that test, so the cell may be colored amber. Add ISBLANK ( v ), BLANK () as the first condition in the SWITCH so the cell gets no color.
Exercise
Write a color measure for [Late Delivery Rate], where lower is better. Use green at or below 2%, amber at or below 5%, and red above 5%. Return no color when the rate is blank.
Show answer
Late Delivery Color = VAR rate = [Late Delivery Rate] RETURN SWITCH ( TRUE (), ISBLANK ( rate ), BLANK (), rate <= 0.02, "#2E7D32", rate <= 0.05, "#F9A825", "#C62828" )