Google表格:如何通过按钮按下来移动某些行以启动功能

时间:2016-04-26 03:48:26

标签: google-sheets

我正在尝试将第4列中包含“x”的行从“a”表批量移动到表单“b”,并从具有指定脚本“按钮”的图片中启动它。有什么建议吗?

function button() {
  var sheetNameToWatch = "a";
  var columnNumberToWatch = 4;
  var valueToWatch = "x";
  var sheetNameToMoveTheRowTo = "b";

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getActiveCell();

  if (sheet.getName() == sheetNameToWatch && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) {
    var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
    var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    sheet.getRange(range.getRow(), 1, 1,sheet.getLastColumn()).moveTo(targetRange);
    sheet.deleteRow(range.getRow());
  }
}

1 个答案:

答案 0 :(得分:0)

我继续制作Google Sheet示例,以显示正在运行的代码。

在这里查看: https://docs.google.com/spreadsheets/d/18GRq2m1TSmdWWFwomjhQi2UM5PVdM1iE8t9fVMO7OXg/edit?usp=sharing

然而,这里的代码很明显,我给你留了一些笔记。

function button() {
  //Set up our variables.
  var sheetA = "a";
  var sheetB = "b";
  var value = "x";
  var column = "D"; //We set the column to "D" because that's the fourth column, it's a lot easier 90% of the time to use column letter over index.
  var rowsToCheck = 10;
  //Variables Specific to Spreadsheet stuff.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  //I noticed that in your code you used "Spreadsheet.getActiveSheet". 
  //Sense we know exactly what sheets we will be using (a,b) we can just grab them by using their name
  var sheet1 = ss.getSheetByName(sheetA);
  var sheet2 = ss.getSheetByName(sheetB);

  //We're going to use a for loop to loop through EACH row in Sheet A. This becomes less efficient when you're scanning through HUGE amounts of rows.
  //If you need to scan through 100+ rows there may be a better alternative. For now, we're scanning 10 (see, var = rowsToCheck).
  for(var i=1;i<=rowsToCheck;i++){
  var range1 = sheet1.getRange(column+i); //column+1 == "D"+i so when i=1, it will be "D1".
    var value = range1.getValue();
    if(value === value){ //In your if statement you were comparing too many values. In if statements you can only compare TWO values. Just a thin to rememeber. :)
      range1.clearContent();
      var range2 = sheet2.getRange(column+i);
      range2.setValue(value);
    }
  }
}

但是,我强烈建议在图像按钮上使用菜单。图像按钮在随机不渲染图像的那一刻有一个奇怪的故障。这可能会导致使用电子表格的人感到很困惑。

您可以在此处阅读有关菜单的信息:https://developers.google.com/apps-script/guides/menus