How do use Google Apps Script to paste down a formula?

Right now I’m able to paste the formula from row X to row Y, however, the calculations in the formulas are the exact same. Say row 1 is A1+B1, the formula for row 5 should be A5+B5.

for  (var x = col; x < lastCol; x++)   {
for  (var j = 2;  j  <= lastRow; j++)   {
var range = sheet.getRange(j,x);

range.setFormula(formulas[0][i]);
}
i++;
}

You can use new method autoFillToNeighbor introduced in October, 2017.

For example if you have three columns with just one formula in cell C2:

View post on imgur.com

then you can autofill rest of C column just with one line of code:

function doTheMagic() {
 SpreadsheetApp.getActiveSheet().getRange("C2").autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
}

Result:

Related One: Insert Date in Google Docs Using Google Apps Scripts

Written By:

Sarmad Gardezi A blog scientist by Mind and a Passionate Blogger by heart. Sarmad is Freelancer, Entrepreneur and Google Apps Scripts Developer from Islamabad, Pakistan.

Subscribe to Email Newsletter