{"record":{"id":"8d3328ca28835372","repo":"PHPOffice/PhpSpreadsheet","slug":"you-tried-to-set-a-sheet-active-by-the-out-of-boun","errorCode":null,"errorMessage":"You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}.","messagePattern":"You tried to set a sheet active by the out of bounds index: (.+?)\\. The actual number of sheets is (.+?)\\.","errorType":"exception","errorClass":"PhpOffice\\PhpSpreadsheet\\Exception","httpStatus":null,"severity":"error","filePath":"src/PhpSpreadsheet/Spreadsheet.php","lineNumber":821,"sourceCode":"     *\n     * @return int Active sheet index\n     */\n    public function getActiveSheetIndex(): int\n    {\n        return $this->activeSheetIndex;\n    }\n\n    /**\n     * Set active sheet index.\n     *\n     * @param int $worksheetIndex Active sheet index\n     */\n    public function setActiveSheetIndex(int $worksheetIndex): Worksheet\n    {\n        $numSheets = count($this->workSheetCollection);\n\n        if ($worksheetIndex > $numSheets - 1) {\n            throw new Exception(\n                \"You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}.\"\n            );\n        }\n        $this->activeSheetIndex = $worksheetIndex;\n\n        return $this->getActiveSheet();\n    }\n\n    /**\n     * Set active sheet index by name.\n     *\n     * @param string $worksheetName Sheet title\n     */\n    public function setActiveSheetIndexByName(string $worksheetName): Worksheet\n    {\n        if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {\n            $this->setActiveSheetIndex($this->getIndex($worksheet));\n","sourceCodeStart":803,"sourceCodeEnd":839,"githubUrl":"https://github.com/PHPOffice/PhpSpreadsheet/blob/65b080eef4d9fd11a5796135ab145883e5c3d6a6/src/PhpSpreadsheet/Spreadsheet.php#L803-L839","documentation":"Spreadsheet::setActiveSheetIndex(int) records which tab is selected when the file opens. It rejects an index beyond the last sheet with this message (the check is an upper-bound test: index > count-1 throws). The returned worksheet is the newly activated one.","triggerScenarios":"setActiveSheetIndex(1) on a single-sheet workbook; a hard-coded 'open on the last tab' using a count captured before sheets were removed; activating an index derived from user input that is 1-based or stale.","commonSituations":"Export pipelines that always 'select the results sheet' by position while the template's tab count varies; code run after removeSheetByIndex() shrinks the collection; UI sheet pickers passing a 1-based number straight through.","solutions":["Clamp before calling: $index = max(0, min($index, $spreadsheet->getSheetCount() - 1));","Prefer selecting by name: $spreadsheet->setActiveSheetIndexByName('Results').","Recompute the count at call time inside loops that add/remove sheets.","Convert 1-based user input to 0-based before calling."],"exampleFix":"// before\n$spreadsheet->setActiveSheetIndex(5); // throws when only 3 sheets\n\n// after\n$spreadsheet->setActiveSheetIndexByName('Results');\n// or\n$index = min(5, $spreadsheet->getSheetCount() - 1);\n$spreadsheet->setActiveSheetIndex($index);","handlingStrategy":"validation","validationCode":"$max = $spreadsheet->getSheetCount() - 1;\n$spreadsheet->setActiveSheetIndex(max(0, min($index, $max)));","typeGuard":"function isValidActiveSheetIndex(\\PhpOffice\\PhpSpreadsheet\\Spreadsheet $s, int $i): bool\n{\n    return $i >= 0 && $i < $s->getSheetCount();\n}","tryCatchPattern":"try {\n    $spreadsheet->setActiveSheetIndex($index);\n} catch (\\PhpOffice\\PhpSpreadsheet\\Exception $e) {\n    $spreadsheet->setActiveSheetIndex(0); // safe default: first tab\n}","preventionTips":["Prefer setActiveSheetIndexByName() with a known title.","Clamp indexes derived from counts that may change at runtime.","Convert 1-based selections from UIs to 0-based."],"tags":["worksheet","index-out-of-bounds","active-sheet","phpspreadsheet"],"backgroundTag":"index-out-of-bounds","analyzedSha":"65b080eef4d9fd11a5796135ab145883e5c3d6a6","analyzedAt":"2026-08-17T05:40:41.646Z","schemaVersion":2},"datasetVersion":"2026-08-17T09:17:11.063Z"}