如何在谷歌电子表格中添加一行并引用另一个单元格?

时间:2012-10-28 21:11:40

标签: google-apps-script google-sheets

我正在尝试创建一个从Google财经中提取数据的功能,并让它自动将数据记录到多张文档中。我似乎无法将它添加为函数,它总是将其添加为文本,直到我编辑单元格

function addLog() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var numLastRows = rows.getLastRow();

  sheet.appendRow(['2012/10/28','=b92','=c92','Log (auto)','','=index(GoogleFinance(C92,"price",A92);2;2)','','=h92','=i92','=j92','=k92']);


};

我无法弄清楚如何让它引用上面的单元格(在本例中为第92行):(

1 个答案:

答案 0 :(得分:2)

您需要使用setFormula()方法而不是appendRow()。也许是这样的事情:

function addLog() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var numLastRow = sheet.getLastRow();

  //add a row at end if necessary
  if (sheet.getMaxRows() == numLastRow) sheet.insertRowAfter(numLastRow);

  sheet.getRange(numLastRow + 1, 2, 1, 10)
    .setFormulas([['=b' + numLastRow,
                  '=c' + numLastRow,
                  '',
                  '',
                  '=index(GoogleFinance(C' + numLastRow + ',"price",A' + numLastRow + ');2;2)',
                  '',
                  '=h' + numLastRow,
                  '=i' + numLastRow,
                  '=j' + numLastRow,
                  '=k' + numLastRow]]);
  sheet.getRange(numLastRow + 1, 1).setValue('2012/10/28');
  sheet.getRange(numLastRow + 1, 4).setValue('Log (auto)');
}

要从第x张到第y张执行此操作(使用从零开始的索引),我认为最有效的方法是:

function addAllLog() {
  var sheets = SpreadsheetApp.getActive().getSheets();
  var x = 1;
  var y = 34;
  for (var i = x; i <= y; i++) {
    addLog(sheets[i]);
  }
}

function addLog(sheet) {
  var numLastRow = sheet.getLastRow();

  //add a row at end if necessary
  if (sheet.getMaxRows() == numLastRow) sheet.insertRowAfter(numLastRow);

  sheet.getRange(numLastRow + 1, 2, 1, 10)
    .setFormulas([['=b' + numLastRow,
                  '=c' + numLastRow,
                  '',
                  '',
                  '=index(GoogleFinance(C' + numLastRow + ',"price",A' + numLastRow + ');2;2)',
                  '',
                  '=h' + numLastRow,
                  '=i' + numLastRow,
                  '=j' + numLastRow,
                  '=k' + numLastRow]]);
  sheet.getRange(numLastRow + 1, 1).setValue('2012/10/28');
  sheet.getRange(numLastRow + 1, 4).setValue('Log (auto)');
}