Google-sheets – Add row to Google Sheets and keep formulas from previous row

google sheetsgoogle-apps-script

I want to add a row to my spreadsheet but keep the formulas – and only the formulas – of the previous row. The #1 solution provided here doesn't help me because it also copies non-formula information, so I tried using .getFormulas() and .setFormulas(), as suggested in solution #2. However, if the last row used, say, some formula containing A36, the new row would still use A36 while it should be using A37. So, how can I keep the formulas from the previous row without this issue? My current code is:

var ss = SpreadsheetApp.getActiveSheet();
var lRow = ss.getLastRow();
var lCol = ss.getLastColumn();
var formulas = ss.getRange(lRow, 1, 1, lCol).getFormulas();
ss.insertRowAfter(lRow);
ss.getRange(lRow + 1, 1, 1, lCol).setFormulas(formulas);

Best Answer

Use getFormulaR1C1 / getFormulasR1C1 and setFormulaR1C1 / setFormulasR1C1

The get methods

Returns the formula (R1C1 notation) for a given cell, or null if none

The set methods

Updates the formula for this range. The given formula must be in R1C1 notation.

Note: On the Google Sheets UI the formulas always are displayed using the A1 Notation.