diff --git a/src/functions/helpers.ts b/src/functions/helpers.ts index 43de5a22e5..151b0b9d3f 100644 --- a/src/functions/helpers.ts +++ b/src/functions/helpers.ts @@ -901,7 +901,9 @@ export function linearSearch( return reverseSearch ? numberOfValues - i - 1 : i; } } - return reverseSearch ? numberOfValues - closestMatchIndex - 1 : closestMatchIndex; + return reverseSearch && closestMatchIndex !== -1 + ? numberOfValues - closestMatchIndex - 1 + : closestMatchIndex; } /** diff --git a/tests/functions/module_lookup.test.ts b/tests/functions/module_lookup.test.ts index f0f7d67a56..83975e2fd5 100644 --- a/tests/functions/module_lookup.test.ts +++ b/tests/functions/module_lookup.test.ts @@ -1319,6 +1319,15 @@ describe("XLOOKUP formula", () => { "#,##0[$$]" ); }); + + test("Empty lookup range with reverse search mode does not crash", () => { + const grid = evaluateGrid({ + A1: "=XLOOKUP(5, B1:B6, C1:C6, , , -1 )", + A2: "=XLOOKUP(5, B1:B6, C1:C6, , , -2 )", + }); + expect(grid.A1).toBe("#N/A"); + expect(grid.A2).toBe("#N/A"); + }); }); describe("INDEX formula", () => {