How do I add a formula like:
=SUM(A1:A17)
to a range of fields using the Google Apps Script API for Google Sheets?
I used the copyTo formula suggested by Frans Van Assche, but used conversions from numeric rows and columns to A1 notation because I didn't have a predefined range. For example, the following code sums each row, not including the header, from column D to however many columns of data were created earlier in the totals column C.
const startRow = 2; // first row to sum
const startCol = 4; // first column to sum
let endCol = sheet.getLastColumn(); // last column with data
let endRow = sheet.getLastRow(); // last row with data
let sumRange = sheet.getRange(startRow, startCol, 1, endCol - startCol + 1); // range for first cell of formula
let copyRange = sheet.getRange(startRow, startCol - 1, endRow - 1, 1); // range to copy formulas into
let sumFormula = "=SUM(" + sumRange.getA1Notation() + ")"; // define formula
let totalsCol = startCol - 1; // this could be whichever column you want the totals to be in, for example, a constant or endCol + 1 if you want the totals at the end
let startCell = sheet.getRange(startRow, totalsCol); // first cell to copy formula into
startCell.setFormula(sumFormula); // add formula to first cell
startCell.copyTo(copyRange); // copy formula from first cell to other range