iOfficeAI/OfficeCLI · error · ArgumentException

Formula contains out-of-range cell reference '{m.Value}'. Ex

Error message

Formula contains out-of-range cell reference '{m.Value}'. Excel limits: rows 1-1048576, columns A-XFD.

What it means

A formula passed to a set/validate operation contains a cell reference whose column exceeds Excel's 16384-column grid (A..XFD) or whose row exceeds 1048576. The library regex-extracts every A1 token from the formula and bounds-checks it so the saved OOXML cannot carry a reference Excel would misinterpret or refuse. This is a write-time guard, not an Excel runtime error.

Source

Thrown at src/officecli/Handlers/Excel/ExcelHandler.Helpers.Validation.cs:312

        // Match A1-style refs: optional $ + 1-3 letters + optional $ + 1-8 digits.
        // (Excel's row ceiling 1048576 is 7-digit, but 8-digit numbers like
        // A10000000 must still be caught so they're rejected with the clean
        // "out-of-range" error rather than slipping through validation.)
        // Avoid matching inside an identifier (e.g. "FOO1") via a leading
        // boundary that requires either start-of-string or a non-letter.
        var rx = new System.Text.RegularExpressions.Regex(
            @"(?<![A-Za-z_])\$?([A-Za-z]{1,3})\$?([0-9]{1,8})\b");
        foreach (System.Text.RegularExpressions.Match m in rx.Matches(stripped))
        {
            var col = m.Groups[1].Value.ToUpperInvariant();
            if (!long.TryParse(m.Groups[2].Value, out var row)) continue;
            // Column index check: ColumnNameToIndex would throw on overflow,
            // but we want a clean validation message. Compute manually.
            int colIdx = 0;
            foreach (var ch in col) colIdx = colIdx * 26 + (ch - 'A' + 1);
            if (colIdx < 1 || colIdx > 16384 || row < 1 || row > 1048576)
            {
                throw new ArgumentException(
                    $"Formula contains out-of-range cell reference '{m.Value}'. " +
                    "Excel limits: rows 1-1048576, columns A-XFD.");
            }
        }
    }

    internal static void ValidateSheetName(string name)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("Invalid sheet name: name cannot be empty or whitespace.");
        if (name.Length > 31)
            throw new ArgumentException(
                $"Invalid sheet name '{name}': length {name.Length} exceeds Excel's 31-char limit.");
        var forbidden = new[] { '\\', '/', '?', '*', ':', '[', ']' };
        var hit = name.IndexOfAny(forbidden);
        if (hit >= 0)
            throw new ArgumentException(
                $"Invalid sheet name '{name}': contains forbidden character '{name[hit]}'. Excel rejects any of: \\ / ? * : [ ]");

View on GitHub (pinned to 1ced45e900)

Solutions

  1. Inspect the formula string: the offending token is quoted verbatim in the message (the {m.Value} placeholder).
  2. Clamp the generated row/col indices to [1,1048576] and [1,16384] before building the A1 string.
  3. Use the library's own ColumnNameToIndex/IndexToColumnName helpers instead of hand-rolling column arithmetic, so overflow is impossible.
  4. If you genuinely need a larger grid, that is not representable in OOXML — redesign to address ranges, not a single mega-cell.

Example fix

// before
sheet.SetFormula("A1", "=XFE1+1");   // column 16385, out of range

// after
sheet.SetFormula("A1", "=XFD1+1");   // column 16384, last legal column
Defensive patterns

Strategy: validation

Validate before calling

static readonly Regex A1Token = new(@"\$?([A-Za-z]{1,3})\$?([0-9]{1,8})");
static void AssertFormulaRefsInBounds(string formula) {
    foreach (Match m in A1Token.Matches(formula)) {
        int col = 0;
        foreach (var ch in m.Groups[1].Value.ToUpperInvariant()) col = col * 26 + (ch - 'A' + 1);
        long row = long.Parse(m.Groups[2].Value);
        if (col < 1 || col > 16384 || row < 1 || row > 1048576)
            throw new ArgumentOutOfRangeException(nameof(formula), $"Out-of-range ref: {m.Value}");
    }
}

Try / catch

try { sheet.SetFormula(cell, formula); }
catch (ArgumentException ex) when (ex.Message.Contains("out-of-range cell reference")) {
    // log the offending token from the message and surface to caller
}

Prevention

When it happens

Trigger: Calling a formula-setting or formula-validation API with a string containing a token like 'A1048577', 'XFE1', 'ZZZ1' (column 18278), or 'A99999999'. The regex `\$?([A-Za-z]{1,3})\$?([0-9]{1,8})` matches the token and the manual colIdx/row bounds check fails.

Common situations: Generated references from unbounded loops; copy-paste from Google Sheets (18,278 columns); a counter that overflowed or was never clamped; an extra digit typo like 'A10485770'.

Related errors


AI-assisted analysis of iOfficeAI/OfficeCLI@1ced45e900 (2026-08-13). Data as JSON: /api/errors/4f47f209e34d62f8. Report an issue: GitHub.