在Google Spreadsheets中,如何在用户点击并激活单元格后,从另一个单元格的值中设置单元格的值?

时间:2014-10-13 02:51:00

标签: javascript google-apps-script google-sheets google-spreadsheet-api

我在Google Spreadsheets中,我知道如何创建新的菜单项,但是如何使用google电子表格appscript代码执行以下操作:

If in cell A2, I click a menuitem "SetValue", then A2's cell value is set with value from A1.
If in cell B2, I click a menuitem "SetValue", then B2's cell value is set with value from B1.
If in cell C2, I click a menuitem "SetValue", then C2's cell value is set with value from C1.
... (and so forth and so on)

请记住,在启动菜单项功能之前,用户可以随意点击第2行中的任何单元格。

2 个答案:

答案 0 :(得分:1)

这是@teatimer的另一个答案中显示的另一个版本的函数,它适用于所有列。我会在评论中写这篇文章,但这本来很难读......

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var cell = ss.getActiveCell();
  var row = cell.getA1Notation().replace(/[^0-9]/g,'');// keep only numeric values
  var column = cell.getA1Notation().replace(/[0-9]/g,'');//remove all numeric characters
  Logger.log('row '+row+'  column '+column);
  if (row != '2') { // row is a string, you must add quotes to get an equal condition
    ss.toast("not valid selection, must be in row 2");
    return;
  }
  var sourceVal = ss.getRange(column+(row - 1)).getValue();
  cell.setValue(sourceVal);
}

您还可以使用其他形式的正则表达式来获得相同的结果:

  var row = cell.getA1Notation().replace(/\d/g,'');// remove non decimal values
  var column = cell.getA1Notation().replace(/\D/g,'');//remove decimal values

答案 1 :(得分:0)

这应该适合你。

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var cell = ss.getActiveCell();
  var row = cell.getA1Notation()[1];
  var column = cell.getA1Notation()[0];
  if (row != 2) {
    ss.toast("not valid selection, must be in row 2");
    return;
  }
  var sourceVal = ss.getRange(column+(row - 1)).getValue();
  cell.setValue(sourceVal);
  return;
}