diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index abef54ffd..ecdb52b17 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -696,8 +696,20 @@ impl<'h> Evaluator<'h> { return err(CellError::Value); } let mut evaluated = Vec::with_capacity(args.len()); - for a in args { - let ev = self.eval(a); + // SUMIF/AVERAGEIF: the size of the criteria range (argument 1), which the sum range takes. + let mut criteria_shape = None; + for (i, a) in args.iter().enumerate() { + let mut ev = self.eval(a); + if resizes_sum_range(name, args.len()) { + if i == 0 { + criteria_shape = ev_shape(&ev); + } else if i == 2 + && let (Some((h, w)), Ev::R(areas)) = (criteria_shape, &ev) + && let [area] = areas.as_slice() + { + ev = Ev::R(vec![Area { sheet: area.sheet, range: resized_sum_range(area.range, h, w) }]); + } + } let from_ref = matches!(ev, Ev::R(_)); let value = match ev { Ev::R(areas) if areas.len() > 1 => { @@ -1306,30 +1318,64 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value) -> Value { } } +/// SUMIF and AVERAGEIF with a sum range: Excel sizes the sum range like the criteria range. +fn resizes_sum_range(name: &str, args: usize) -> bool { + args == 3 && matches!(name, "SUMIF" | "AVERAGEIF") +} + +/// Height and width of a single-area reference or an array argument. +fn ev_shape(ev: &Ev) -> Option<(u32, u32)> { + match ev { + Ev::R(areas) => match areas.as_slice() { + [a] => Some((a.range.height(), a.range.width())), + _ => None, + }, + Ev::V(Value::Array(a)) => Some((u32::try_from(a.rows).unwrap_or(u32::MAX), u32::try_from(a.cols).unwrap_or(u32::MAX))), + Ev::V(_) => Some((1, 1)), + Ev::L(_) => None, + } +} + +/// The range SUMIF/AVERAGEIF add up: from the sum range's top-left cell, as many rows and columns +/// as the criteria range (`height` × `width`), cut off at the sheet's edge. +pub fn resized_sum_range(sum: RangeRef, height: u32, width: u32) -> RangeRef { + let row = sum.start.row.saturating_add(height.saturating_sub(1)).min(MAX_ROWS - 1); + let col = sum.start.col.saturating_add(width.saturating_sub(1)).min(MAX_COLS - 1); + RangeRef::new(sum.start, CellRef::new(row, col)) +} + /// Collects the static references of an expression with their sheets resolved; `dynamic` is /// set when the formula uses INDIRECT/OFFSET/names/tables whose targets can change. pub fn precedents(wb: &Workbook, sheet: usize, e: &Expr) -> (Vec, bool) { let mut out = Vec::new(); let mut dynamic = false; - e.walk(&mut |x| match x { - Expr::Ref(r) => { - let range = r.range(); - match &r.sheet { - SheetSel::Current => out.push(Area { sheet, range }), - SheetSel::Named(n) => { - if let Some(i) = wb.sheet_index(n) { - out.push(Area { sheet: i, range }); - } - } - SheetSel::Span(a, b) => { - if let (Some(i), Some(j)) = (wb.sheet_index(a), wb.sheet_index(b)) { - for s in i.min(j)..=i.max(j) { - out.push(Area { sheet: s, range }); - } - } + let push = |out: &mut Vec, r: &Reference, range: RangeRef| match &r.sheet { + SheetSel::Current => out.push(Area { sheet, range }), + SheetSel::Named(n) => { + if let Some(i) = wb.sheet_index(n) { + out.push(Area { sheet: i, range }); + } + } + SheetSel::Span(a, b) => { + if let (Some(i), Some(j)) = (wb.sheet_index(a), wb.sheet_index(b)) { + for s in i.min(j)..=i.max(j) { + out.push(Area { sheet: s, range }); } } } + }; + e.walk(&mut |x| match x { + Expr::Ref(r) => push(&mut out, r, r.range()), + // The cells SUMIF/AVERAGEIF really read from the sum range (see `resized_sum_range`); when + // the criteria range's size isn't known statically, recalculate the formula every time. + Expr::Call(n, args) if resizes_sum_range(n, args.len()) => match (args.first(), args.get(2)) { + (Some(Expr::Ref(c)), Some(Expr::Ref(s))) => { + let (crit, sum) = (c.range(), s.range()); + push(&mut out, s, resized_sum_range(sum, crit.height(), crit.width())); + } + (_, Some(Expr::Number(_) | Expr::Text(_) | Expr::Bool(_) | Expr::Error(_) | Expr::Array(_) | Expr::Missing)) => {} + _ => dynamic = true, + }, Expr::Call(n, _) if matches!(n.as_str(), "INDIRECT" | "OFFSET" | "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" | "CELL" | "INFO") => { diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 67db0830d..255bf7fe0 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -215,3 +215,94 @@ fn recalc_all_after_load() { t.calc.recalc_all(&mut t.wb); assert_eq!(t.num("A3"), 12.0); } + +#[test] +fn sumif_sum_range_takes_the_criteria_size() { + // Excel adds up the range that starts at sum_range's top-left cell with the criteria range's + // height and width, whatever size sum_range has. + let mut t = T::new(); + for (r, (k, v)) in [("a", 1), ("b", 2), ("a", 3)].iter().enumerate() { + t.set(&format!("A{}", r + 1), k); + t.set(&format!("B{}", r + 1), &v.to_string()); + } + t.set("D1", "=SUMIF(A1:A3,\"a\",B1)"); + assert_eq!(t.num("D1"), 4.0); + t.set("D2", "=AVERAGEIF(A1:A3,\"a\",B1)"); + assert_eq!(t.num("D2"), 2.0); + t.set("D3", "=SUMIF(A1:A3,\"a\",B1:B2)"); + assert_eq!(t.num("D3"), 4.0); + t.set("D4", "=SUMIF(A1:A3,\"a\",B1:F1)"); + assert_eq!(t.num("D4"), 4.0); + t.set("D5", "=SUMIF(A1:A3,\"a\",B1:B99)"); + assert_eq!(t.num("D5"), 4.0); + t.set("D6", "=SUMIF(A:A,\"a\",B1)"); + assert_eq!(t.num("D6"), 4.0); + t.set("D7", "=SUMIF(A1:A3,\"a\",$B$2)"); + assert_eq!(t.num("D7"), 2.0); // B2:B4: rows 1 and 3 match → B2 + B4 (empty) + t.set("D8", "=SUMIF(A1:A3,\"a\")"); + assert_eq!(t.num("D8"), 0.0); + // A horizontal criteria range resizes across. + t.set("H1", "1"); + t.set("I1", "0"); + t.set("J1", "1"); + t.set("H2", "10"); + t.set("I2", "20"); + t.set("J2", "30"); + t.set("D9", "=SUMIF(H1:J1,1,H2)"); + assert_eq!(t.num("D9"), 40.0); + // The resized cells are precedents: editing one recalculates. + t.set("B3", "5"); + assert_eq!(t.num("D1"), 6.0); + assert_eq!(t.num("D2"), 3.0); + assert_eq!(t.num("D3"), 6.0); + assert_eq!(t.num("D4"), 6.0); + assert_eq!(t.num("D6"), 6.0); + // SUMIFS and AVERAGEIFS don't resize: different sizes are #VALUE!. + t.set("D11", "=SUMIFS(B1,A1:A3,\"a\")"); + assert_eq!(t.get("D11"), Value::Error(CellError::Value)); + t.set("D12", "=AVERAGEIFS(B1:B2,A1:A3,\"a\")"); + assert_eq!(t.get("D12"), Value::Error(CellError::Value)); + t.set("D13", "=SUMIFS(B1:B3,A1:A3,\"a\")"); + assert_eq!(t.num("D13"), 6.0); +} + +#[test] +fn sumif_resized_sum_range_stops_at_the_sheet_edge() { + let mut t = T::new(); + t.set("A1", "a"); + t.set("A2", "a"); + t.set("B1048575", "5"); + t.set("B1048576", "7"); + t.set("C1", "=SUMIF(A1:A2,\"a\",B1048576)"); + assert_eq!(t.num("C1"), 7.0); + t.set("C2", "=SUMIF(A1:A2,\"a\",B1048575)"); + assert_eq!(t.num("C2"), 12.0); + t.set("C3", "=SUMIF(A1:B1,\"a\",XFD1)"); + assert_eq!(t.num("C3"), 0.0); +} + +#[test] +fn sumif_resized_sum_range_on_another_sheet_and_through_a_name() { + let mut t = T::new(); + t.wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Data"))); + t.wb.names.push(gridcraft_model::DefinedName { + name: "Amounts".into(), + scope: None, + formula: "Data!$B$1".into(), + comment: String::new(), + hidden: false, + }); + for (r, k) in ["a", "b", "a"].iter().enumerate() { + t.set(&format!("A{}", r + 1), k); + t.wb.sheet_mut(1).unwrap().set_value(CellRef::new(r as u32, 1), Value::Number((r + 1) as f64)); + } + t.calc.rebuild(&t.wb); + t.set("C1", "=SUMIF(A1:A3,\"a\",Data!B1)"); + assert_eq!(t.num("C1"), 4.0); + t.set("C2", "=AVERAGEIF(A1:A3,\"a\",Amounts)"); + assert_eq!(t.num("C2"), 2.0); + t.wb.sheet_mut(1).unwrap().set_value(c("B3"), Value::Number(9.0)); + t.calc.cells_changed(&mut t.wb, &[(1, c("B3"))]); + assert_eq!(t.num("C1"), 10.0); + assert_eq!(t.num("C2"), 5.0); +} diff --git a/crates/functions/src/math.rs b/crates/functions/src/math.rs index 3a0bab385..8196f5a79 100644 --- a/crates/functions/src/math.rs +++ b/crates/functions/src/math.rs @@ -1006,8 +1006,9 @@ fn countif(a: &[Arg], _c: &mut dyn Ctx) -> R { num_val(range.iter().filter(|v| c.matches(v)).count() as f64) } -/// SUMIF / AVERAGEIF: matched numbers from the sum range, which takes the criteria range's -/// shape anchored at its own top-left. +/// SUMIF / AVERAGEIF: matched numbers from the sum range, read at the criteria range's positions. +/// Excel sizes a sum range reference like the criteria range, anchored at its own top-left cell; +/// the evaluator does that resizing (it has the references), so cells line up one to one here. fn if_numbers(a: &[Arg]) -> R> { let range = as_array(&crate::util::arg(a, 0)?.value); let c = Criterion::parse(&crate::util::arg(a, 1)?.value.scalar());