diff --git a/src/PhpSpreadsheet/Cell/Cell.php b/src/PhpSpreadsheet/Cell/Cell.php index 0bca2fc0..74ed9268 100644 --- a/src/PhpSpreadsheet/Cell/Cell.php +++ b/src/PhpSpreadsheet/Cell/Cell.php @@ -251,9 +251,11 @@ class Cell { if ($this->dataType == DataType::TYPE_FORMULA) { try { + $index = $this->getWorksheet()->getParent()->getActiveSheetIndex(); $result = Calculation::getInstance( $this->getWorksheet()->getParent() )->calculateCellValue($this, $resetLog); + $this->getWorksheet()->getParent()->setActiveSheetIndex($index); // We don't yet handle array returns if (is_array($result)) { while (is_array($result)) { diff --git a/tests/PhpSpreadsheetTests/Cell/CellTest.php b/tests/PhpSpreadsheetTests/Cell/CellTest.php index 8c95e864..0d9ce337 100644 --- a/tests/PhpSpreadsheetTests/Cell/CellTest.php +++ b/tests/PhpSpreadsheetTests/Cell/CellTest.php @@ -46,4 +46,23 @@ class CellTest extends TestCase { return require 'tests/data/Cell/SetValueExplicitException.php'; } + + public function testNoChangeToActiveSheet(): void + { + $spreadsheet = new Spreadsheet(); + $sheet1 = $spreadsheet->getActiveSheet(); + $sheet1->setTitle('Sheet 1'); + $sheet3 = $spreadsheet->createSheet(); + $sheet3->setTitle('Sheet 3'); + $sheet1->setCellValue('C1', 123); + $sheet1->setCellValue('D1', 124); + $sheet3->setCellValue('A1', "='Sheet 1'!C1+'Sheet 1'!D1"); + $sheet1->setCellValue('A1', "='Sheet 3'!A1"); + $cell = 'A1'; + $spreadsheet->setActiveSheetIndex(0); + self::assertEquals(0, $spreadsheet->getActiveSheetIndex()); + $value = $spreadsheet->getActiveSheet()->getCell($cell)->getCalculatedValue(); + self::assertEquals(0, $spreadsheet->getActiveSheetIndex()); + self::assertEquals(247, $value); + } }