如何使用Google Apps脚本向Google电子表格添加公式? [英] How do I add formulas to Google Spreadsheet using Google Apps Script?

查看:119
本文介绍了如何使用Google Apps脚本向Google电子表格添加公式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 = SUM(A1:A17)等公式添加到使用Google电子表格的Google Apps Script API的一系列字段中?

How do I add a formula like =SUM(A1:A17) to a range of fields using the Google Apps Script API for Google Spreadsheets?

推荐答案

使用 setFormula 。下面是一个如何做到这一点的例子。

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

您也可以使用 setFormulaR1C1 创建R1C1表示法公式。下面的例子。

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

若要将几个公式添加到多个字段,请使用 setFormulas 。下面的例子

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

这篇关于如何使用Google Apps脚本向Google电子表格添加公式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆