67

How do I add a formula like:

=SUM(A1:A17)

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

1
  • Are you looking for the same formula =SUM(A1:A17) in a range of cells, or do you want to change the range within the sum based on where you are in the sheet? Jul 16, 2020 at 11:14

5 Answers 5

104

This is done using the setFormula for a selected cell. Below is an example of how to do this.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B5");
cell.setFormula("=SUM(B3:B4)");

You can also use setFormulaR1C1 to create R1C1 notation formulas. Example below.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B5");
// This sets the formula to be the sum of the 3 rows above B5
cell.setFormulaR1C1("=SUM(R[-3]C[0]:R[-1]C[0])");

To add several formulas to several fields use setFormulas. Example below

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// This sets the formulas to be a row of sums, followed by a row of averages right below.
// The size of the two-dimensional array must match the size of the range.
var formulas = [
  ["=SUM(B2:B4)", "=SUM(C2:C4)", "=SUM(D2:D4)"],
  ["=AVERAGE(B2:B4)", "=AVERAGE(C2:C4)", "=AVERAGE(D2:D4)"]
];

var cell = sheet.getRange("B5:D6");
cell.setFormulas(formulas);
3
  • For info, this is a very bad answer...no idea why it has been accepted and up voted. Refer to documentation to see how to get a range, setFormula is a range method (and it was so in 2012 as well :-) Nov 1, 2014 at 9:42
  • 22
    @Sergeinsas please post your method then Nov 12, 2014 at 1:45
  • I think setFormula works but I agree that how to use it should be described better in the answer instead of focusing on how to select the cell. Nov 12, 2014 at 7:24
8

Here's a more general answer.

Suppose you want to populate column B with a formula that is the value of column A, plus 1. For example,the formula in cell B1 would be "=A1 + 1".

Let's stipulate that first row of the range is 1, and the last is 20.

// create an array the same size as the number of rows.
var data = [];
// populate the array with the formulas.
for (var i=0; i < 20; i++)
{
  // note that as usual, each element of the array must itself be an array 
  // that has as many elements as columns. (1, in this case.)
    data[i] = ['=A' + (i+1).toString() + ' + 1 ' ];
}
// set the column values.
sheet.getRange(1,2,20,1).setFormulas(data);

Making this work for different numbers of rows, and different starting row, is a matter of using variables instead of the hard-coded 1 and 20 in this example.

0
5

Set, Copy & Paste in a range

If you want for example A18 to hold the formula '=SUM(A1:A17)' and the same for columns B to Z you can set the formula in A18 and then copy A18 to B18:Z18. The same thing holds for more complicated ranges. The easiest to get going is to use the macro recorder and then inspect your script.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
sheet.getRange('A18').setFormula('=SUM(A1:A17)');
sheet.getRange('A18').copyTo(sheet.getRange('B18:Z18'));
//There are other parameters to 'copyTo' that you can use if needed
2
  • The three-parameter copyTo isn't necessary, because the defaults are already PASTE_NORMAL and false (don't transpose). Nothing wrong with using the single-parameter short version, right? Jul 29, 2020 at 10:03
  • Yes Martin, you are right. I made the example code more succinct now with the comment that there are other parameters for the 'copyTo' function that can be used if needed. Jul 30, 2020 at 22:02
4

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
3

setValues() is also working in place of setFormulas()

  var disht = spss.getSheetByName("DI");
  var divals = disht.getRange("A1:G50").getValues();
  divals[40][5]= "=round(SUM(F10:F39),0)"; //F41 =round(SUM(F10:F39),0)
  divals[42][5]= "=(F42+F41)*(F8/100)";  //F43 =(F42+F41)*(F8/100)
  divals[43][5]= '=if(G8>0,(F41+F42)*(G8/100),"")' ; //F44 =if(G8>0,(F41+F42)*(G8/100),"")
  divals[44][5]= '=if(isblank($G$7),"",sum($F$41:$F$44)*$G$7*0.01)';//F45 =if(isblank($G$7),"",sum($F$41:$F$44)*$G$7*0.01)
  divals[45][5]= '=round(F41,0)+round(F42,0)+round(F43,0)+round(F44,0)+round(F45,0)' ; //F46 =round(F41,0)+round(F42,0)+round(F43,0)+round(F44,0)+round(F45,0)
  divals[47][5]= "=F46-F47"; //F48 =F46-F47
  divals[44][4]= '=if(isblank($G$7),"","TCS")'; //E45  =if(isblank($G$7),"","TCS")
  disht.getRange("A1:G50").setValues(divals);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.