如何添加公式来使用谷歌Apps脚本谷歌表?(How do I add formulas to Goo

2019-06-17 19:26发布

如何添加一个公式,如:

=SUM(A1:A17)

到一系列使用谷歌表格中谷歌Apps脚本API领域的?

Answer 1:

这是使用进行setFormula为选定的单元格。 下面是如何做到这一点的例子。

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

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

您还可以使用setFormulaR1C1创建R1C1表示法的公式。 下面的实施例。

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])");

为了给几个领域使用添加几个公式setFormulas 。 下面的示例

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);


Answer 2:

这里有一个更普遍的回答。

假设你想用一个公式,是列A的值,加上1。例如填充塔B,在B1单元格式将是“= A1 + 1”。

让我们规定了一系列的第一行是1,最后是20。

// create an array the same size as the number of rows.
var data = new Array[20];
// 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)

使这项工作对于不同数量的行,不同的起始行,是使用变量,而不是问题的硬编码在这个例子中1和20。



文章来源: How do I add formulas to Google Sheets using Google Apps Script?