Have AI explain an inherited nested formula, then test it
Break down inherited nested IF formulas into indented logic and rule tables, then verify them against 8 boundary test cases and an IFS rewrite.
When inheriting a workbook with a six-level nested IF formula, modifying it without a verified rule table risks silent calculation errors. Deconstruct the formula execution order and boundary rules with AI, then verify both the original formula and an IFS rewrite against eight boundary test cases. Related data validation workflows appear in table validation.
[1] Define the target formula and reference columns. This sample formula determines performance grades (S, A+, A, B, C, D, F) based on target sales achievement and review scores.
=IF(AND(B2>=120,C2>=90),"S",IF(AND(B2>=100,C2>=85),"A+",IF(B2>=100,"A",IF(AND(B2>=80,C2>=70),"B",IF(B2>=70,"C",IF(C2<60,"F","D"))))))The referenced columns are:
B2: Sales Achievement Rate (%)C2: Performance Evaluation Score (0-100)
The formula nests six IF conditions mixing AND criteria with single thresholds. Because IF evaluates sequentially from left to right and halts at the first TRUE condition, downstream branches depend on all preceding tests evaluating to FALSE. For instance, step 3 (B2>=100) is only reached when both step 1 (B2>=120 AND C2>=90) and step 2 (B2>=100 AND C2>=85) fail. Reading raw parentheses makes tracking precedence error-prone.
[2] Construct the formula deconstruction prompt. Require four outputs: an indented formula, a priority rule table, eight boundary test cases, and an equivalent IFS rewrite.
Please analyze the following Excel formula. [Formula]{Formula} [Reference Columns]{Column Descriptions} [Requirements]1. Indented Formula: Format the formula with indentation and line breaks to show the nested structure clearly.2. Rule Table: Create a Markdown table with evaluation priority (Steps 1-7), condition, resulting grade, and explanation.3. 8 Boundary Test Cases: Provide 8 test cases that test critical boundaries (120, 100, 80, 70, 60) and edge cases in a Markdown table. (Columns: No | B2 | C2 | Expected Grade | Test Objective)4. Simplified IFS Formula: Rewrite the equivalent logic using the IFS function.Microsoft's Copilot in Excel guide suggests requesting step-by-step condition breakdowns to inspect complex cell formulas. Plain prose explanations often hide edge-case misunderstandings, so requesting structured test inputs and expected grades allows direct verification against actual spreadsheet calculations.
[3] Execute the prompt with the formula and column descriptions.
$ claude -p --model claude-sonnet-5-5 --max-turns 1 --tools "" --setting-sources "" --strict-mcp-config < run/explain.en.prompt.txt > run/explain.en.1.out.txtThe output returns the indented formula, the rule table, eight boundary cases, and the IFS replacement.
## 1. Indented Formula =IF(AND(B2>=120, C2>=90), "S", IF(AND(B2>=100, C2>=85), "A+", IF(B2>=100, "A", IF(AND(B2>=80, C2>=70), "B", IF(B2>=70, "C", IF(C2<60, "F", "D") ) ) ) )) … ## 2. Rule Table Each step is evaluated only if all earlier steps were false, so every step implicitly includes "not matched above". | Step | Condition | Grade | Explanation ||---|---|---|---|| 1 | B2 ≥ 120 AND C2 ≥ 90 | S | Top tier: both sales and evaluation are excellent. || 2 | B2 ≥ 100 AND C2 ≥ 85 | A+ | Target met, with a high evaluation score. This also catches B2 ≥ 120 when C2 is 85-89. || 3 | B2 ≥ 100 | A | Target met but C2 < 85. The evaluation score no longer matters, even if it is very low. |…| 7 | Otherwise | D | B2 < 70 and C2 ≥ 60. | … ## 3. Boundary Test Cases | No | B2 | C2 | Expected Grade | Test Objective ||---|---|---|---|---|| 1 | 120 | 90 | S | Exact lower bounds of both S conditions (B2 = 120, C2 = 90). || 2 | 119 | 85 | A+ | One below the 120 boundary (no S), and exactly at the C2 = 85 boundary. || 3 | 100 | 84 | A | Exactly at B2 = 100, with C2 one below 85 (A+ fails, A applies). |…| 7 | 69 | 60 | D | One below the 70 boundary, and exactly at C2 = 60 (not F). || 8 | 69 | 59 | F | One below both 70 and 60, the only path to F. | ## 4. Simplified IFS Formula =IFS( AND(B2>=120, C2>=90), "S", AND(B2>=100, C2>=85), "A+", B2>=100, "A", AND(B2>=80, C2>=70), "B", B2>=70, "C", C2<60, "F", TRUE, "D")…Comparing with a second run (run/explain.en.2.out.txt), both executions generated identical rule hierarchies and identical IFS formulas. Minor input differences appeared in case 2 (119, 85 vs 119, 100), case 4 (99, 70 vs 99, 100), and case 6 (70, 59 vs 70, 0), but all eight cases in both iterations matched the original formula behavior.
[4] Verify the test cases and formula equivalence with a test script.
In Excel, enter the eight pairs of test values into blank cells and check whether the original formula matches the expected grades. Place the new IFS formula in an adjacent column and verify full equivalence with =SUMPRODUCT(--(D2:D9<>E2:E9)) or across the entire dataset with =SUM(--(original_col<>new_col)).
The verification script uses only the Python standard library. It reads the original formula (run/formula.txt) and **the IFS formula the model wrote in its answer**, evaluates both in Python, and checks (1) that the model's 8 test cases have no duplicated inputs and match both the original formula and the model's expected grades, and (2) that the original and the model's IFS agree on every point of an integer grid of 15,251 points (achievement 0-150 x score 0-100). It does not test fractional values or blank or text cells.
import re, sys ENV = {"IF": lambda c, a, b: a if c else b, "IFS": lambda *p: next(v for k, v in zip(p[::2], p[1::2]) if k), "AND": lambda *a: all(a), "OR": lambda *a: any(a), "TRUE": True} def compile_formula(text): src = text.strip().lstrip("=") if set(re.findall(r"[A-Za-z_][A-Za-z0-9_]*", re.sub(r'"[^"]*"', "", src))) - set(ENV) - {"B2", "C2"}: raise ValueError("Disallowed name: " + src[:40]) code = compile(src, "<formula>", "eval") return lambda b, c: eval(code, {"__builtins__": {}}, {**ENV, "B2": b, "C2": c}) def model_ifs(path): lines = open(path, encoding="utf-8").read().splitlines() i = next(n for n, l in enumerate(lines) if l.strip().startswith("=IFS(")) text, depth = "", 0 for l in lines[i:]: text += l.strip() depth += l.count("(") - l.count(")") if depth == 0: return text def verify(path): orig = compile_formula(open("run/formula.txt", encoding="utf-8").read()) ifs = compile_formula(model_ifs(path)) cases, seen, bad = [], set(), 0 for l in open(path, encoding="utf-8"): r = [c.strip() for c in l.strip().split("|")[1:-1]] if len(r) >= 4 and r[0].isdigit(): try: cases.append((r[0], float(r[1]), float(r[2]), r[3])) except ValueError: pass # rule-table rows and other lines that are not numeric inputs for no, b, c, exp in cases: act = orig(b, c) if (b, c) in seen or act != exp or act != ifs(b, c): bad += 1 print(f"FAIL {no}: ({b:g},{c:g}) exp={exp} act={act}" + (" duplicate input" if (b, c) in seen else "")) else: print(f"OK {no}: ({b:3.0f},{c:3.0f}) -> {exp}") seen.add((b, c)) grid = [(b, c) for b in range(151) for c in range(101)] grid_bad = sum(1 for b, c in grid if orig(b, c) != ifs(b, c)) print(f"{len(cases)} cases, grid {len(grid)} points, grid diff: {grid_bad}") return len(cases) == 8 and bad == 0 and grid_bad == 0 if __name__ == "__main__": sys.exit(0 if verify(sys.argv[1]) else 1)Run the verification against the first run output.
$ python run/verify_en.py run/explain.en.1.out.txtOK 1: (120, 90) -> S…OK 8: ( 69, 59) -> F8 cases, grid 15251 points, grid diff: 0All eight cases passed, and the two formulas differed at 0 of the 15,251 grid points. The exit code is 0. The second run output (run/explain.en.2.out.txt) passed the same way.
To see whether the script rejects bad input, three hand-edited copies of the run 1 output were tested, and all exited with code 1 (not model output): (1) case 3's expected grade changed to A+, (2) case 5's input changed to the same 99, 70 as case 4 so the inputs repeat, and (3) B2>=70 in the IFS formula changed to B2>=75. The failing lines for (1) and (3) are shown.
$ python run/verify_en.py run/bad_en_wrong_expected.txtFAIL 3: (100,84) exp=A+ act=A$ python run/verify_en.py run/bad_en_ifs_formula.txtFAIL 6: (70,59) exp=C act=C8 cases, grid 15251 points, grid diff: 505(For (1) only the FAIL 3 line is copied, and for (3) the FAIL 6 line and the grid line. The full results are in run/vout.*.txt.) (This is not model output. These are results for hand-edited test files.)
[5] Address edge-case weaknesses identified in the output.
First, blank cells and text strings introduce hidden risks. Excel treats an empty cell as 0 in a comparison. An empty C2 does not by itself give F: if B2 is 100 or more the grade is already A+ or A, and if B2 is 70 or more it is C. F appears only when B2<70 and C2 is below 60 (an empty cell counts). Conversely, Excel compares text as greater than any number, so entering "Pending" into B2 makes B2>=120 true and returns S whenever C2>=90 as well. This run did not test either behavior in Excel; both come from reading the evaluation order of the formula. Use Excel Data Validation or add defensive prefix checks to reject non-numeric entries.
Second, business rule assumptions need review. Step 5 (B2>=70) ignores C2 entirely. For achievement from 70 up to 100 that no earlier step catches (for example 70 to 79), the grade is C even with a performance score of 0; at 100 or more an earlier step has already given A or better. Verify with stakeholders whether low evaluation scores should trigger an automatic F.
Third, the IFS function requires an explicit fallback. While nested IF supplies a final ELSE argument ("D"), IFS lacks a default syntax. Omitting TRUE, "D" at the end results in #N/A errors for non-matching rows. IFS requires Excel 2019 or Microsoft 365.
Here is the defensive formula incorporating validation guards:
=IF(OR(ISBLANK(B2),ISBLANK(C2),NOT(ISNUMBER(B2)),NOT(ISNUMBER(C2))),"Check Input",IFS(AND(B2>=120,C2>=90),"S",AND(B2>=100,C2>=85),"A+",B2>=100,"A",AND(B2>=80,C2>=70),"B",B2>=70,"C",C2<60,"F",TRUE,"D"))