61

次のような数式を追加するにはどうすればよいですか。

=SUM(A1:A17)

Google スプレッドシート用の Google Apps Script API を使用してさまざまなフィールドに

4

5 に答える 5

92

これは、選択したセルの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);
于 2012-08-20T12:42:37.023 に答える
7

これがより一般的な答えです。

列 A の値に 1 を加えた数式を列 B に入力するとします。たとえば、セル B1 の数式は "=A1 + 1" になります。

範囲の最初の行が 1 で、最後の行が 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);

異なる数の行と異なる開始行に対してこれを機能させるには、この例でハードコーディングされた 1 と 20 の代わりに変数を使用するだけです。

于 2019-05-08T01:14:46.253 に答える
5

範囲で設定、コピー&ペースト

たとえば、A18 に数式 '=SUM(A1:A17)' を保持させ、列 B から Z まで同じようにする場合は、A18 に数式を設定してから、A18 を B18:Z18 にコピーできます。同じことが、より複雑な範囲にも当てはまります。最も簡単な方法は、マクロ レコーダーを使用してスクリプトを検査することです。

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
于 2020-05-20T15:48:18.127 に答える