function fillEmptyRowsWithFixedMonthSafe() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
sheets.filter(sheet => !sheet.isSheetHidden()).forEach(function (sheet) {
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
if (lastRow < 2) return;
var values = sheet.getRange(1, 1, lastRow + 1, lastCol).getValues();
var formulas = sheet.getRange(1, 1, lastRow + 1, lastCol).getFormulas();
lastRow = lastRow + 1;
for (var i = 1; i < lastRow; i++) {
var currentRowValues = values[i];
var currentRowFormulas = formulas[i];
var isRowEmpty = currentRowValues.every(
(cell, idx) => (cell === "" || cell === null) && currentRowFormulas[idx] === ""
);
if (isRowEmpty) {
var prevRowFormulas = formulas[i - 1];
var prevRowValues = values[i - 1];
var isPrevRowEmpty = prevRowValues.every(
(cell, idx) => (cell === "" || cell === null) && prevRowFormulas[idx] === ""
);
var monthValue = prevRowValues[1];
var monthFormula = prevRowFormulas[1];
var hasOldMonth =
(monthValue && monthValue.toString().includes("06.26")) ||
(monthFormula && monthFormula.includes("06.26"));
if (!isPrevRowEmpty && hasOldMonth) {
var newFormulas = [];
for (var j = 0; j < lastCol; j++) {
var formula = prevRowFormulas[j];
if (formula && formula.startsWith("=")) {
// J–AA (индексы 9–26)
if (j >= 9 && j <= 26) {
formula = incrementRowReferences(formula, 1);
}
formula = formula.replace(/06\.26/g, "07.26");
newFormulas[j] = formula;
} else {
newFormulas[j] = "";
}
}
var targetRange = sheet.getRange(i + 1, 1, 1, lastCol);
targetRange.setFormulas([newFormulas]);
sheet.getRange(i, 1, 1, lastCol)
.copyTo(targetRange, SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
targetRange.setBorder(
true,
null,
null,
null,
null,
null,
"#000000",
SpreadsheetApp.BorderStyle.SOLID
);
Logger.log("Заполнена строка " + (i + 1) + " — " + sheet.getName());
}
while (i + 1 < lastRow) {
var nextValues = values[i + 1];
var nextFormulas = formulas[i + 1];
var nextIsEmpty = nextValues.every(
(cell, idx) => (cell === "" || cell === null) && nextFormulas[idx] === ""
);
if (!nextIsEmpty) break;
i++;
}
}
}
});
}
function incrementRowReferences(formula, increment) {
return formula.replace(/([A-Z]+)(\d+)/g, function (_, col, row) {
return col + (parseInt(row, 10) + increment);
});
}