function onFormSubmit(e) {
var sheetName = 'Form Responses 1';
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var lastRow = sheet.getLastRow();
var formulaRow = 2; // Row that contains the formulas
var newRow = lastRow; // The new row where the formulas will be copied
// Get the range of the formulas in the second row
var formulaRange = sheet.getRange(formulaRow, 1, 1, sheet.getLastColumn());
var formulas = formulaRange.getFormulas()[0]; // Get formulas as strings
// Get the range of the new row
var newRowRange = sheet.getRange(newRow, 1, 1, sheet.getLastColumn());
// Loop through each formula
formulas.forEach(function(formula, columnIndex) {
if (formula) {
// Adjust the formula to refer to the new row
var adjustedFormula = formula.replace(/\$?([A-Z]+\d+)/g, function(match) {
if (match.startsWith('$')) {
// Preserve absolute reference
return match;
} else {
// Extract the column and row parts
var columnPart = match.match(/[A-Z]+/)[0];
var rowPart = match.match(/\d+/)[0];
// Adjust row reference to new row
var newRowIndex = parseInt(rowPart) + (newRow - formulaRow);
return columnPart + newRowIndex;
}
});
// Set the adjusted formula in the new row only if there was a formula in the original cell
if (adjustedFormula !== "") {
newRowRange.getCell(1, columnIndex + 1).setFormula(adjustedFormula);
} else {
// Clear the cell in the new row if there was no formula in the original cell
newRowRange.getCell(1, columnIndex + 1).clear({contentsOnly: true});
}
}
});
}