How do I add formulas to Google Sheets using Google Apps Script?

后端 未结 4 1087
我寻月下人不归
我寻月下人不归 2020-11-30 02:49

How do I add a formula like:

=SUM(A1:A17)

to a range of fields using the Google Apps Script API for Google Sheets?

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 03:25

    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
    

提交回复
热议问题