工作表中出现新行触发的脚本

时间:2019-11-22 14:15:58

标签: google-apps-script google-sheets

我使用的是外部来源的snapData脚本,如下所示:

    function snapData() {

    // get current sheet and tabs 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); var current = ss.getSheetByName('Fees (management)'); var database = ss.getSheetByName('Fees (data)');

    // count rows to snap var current_rows = current.getLastRow(); 
    var database_rows = database.getLastRow() + 1; 
    var database_rows_new = current_rows + database_rows - 2; 
    var rows_new = current.getRange("A2:F" + current_rows).getValues();

    // snap rows, can run this on a trigger to be timed 
    database.getRange("A" + database_rows + ":F" + database_rows_new).setValues(rows_new);

    }

目前,它是通过按“运行”按钮触发的,但是我希望脚本由新行触发,该行出现在另一个选项卡上。

对此将有所帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

“我希望由新行触发的脚本出现在另一个选项卡上。”

通过使用可安装的触发器onChange,可以按计划触发脚本。 sourceonChange返回的事件对象,尽管它不包含在documnentation中。

  • var sheetname = src.getActiveSheet().getSheetName():获取工作表名称
  • var ctype = e.changeType;:获取更改类型
  • if (sheetname === "target" && ctype === "INSERT_ROW"){:测试类型是否在“目标”上插入行

function so5899606501(e) {

  // return all the event objects
  Logger.log(JSON.stringify(e));

  // get the source
  var src = e.source;
  var spreadsheetname = src.getName();
  var sheetname = src.getActiveSheet().getSheetName()
  Logger.log("spreadsheet = "+spreadsheetname+", sheet name = "+sheetname);
  var currentcell = src.getCurrentCell();
  Logger.log("the current cell = "+currentcell.getA1Notation());

  // get the change type
  var ctype = e.changeType;
  Logger.log("the change type is "+ctype);

  // test for the type of change
  if (ctype == "INSERT_ROW"){  
  Logger.log("A row was just inserted");
  }
  else
  {
  Logger.log("the change type wasnt a new row, it was "+ctype)
  }

  //test for the sheet where the change took place
  if (sheetname == "target"){  
  Logger.log("the change took place on the sheet named 'target'");
  }
  else
  {
  Logger.log("the change took place on the sheet named" +sheetname+".")
  }

  // test for the change type AND the sheet name
  if (sheetname == "target" && ctype == "INSERT_ROW"){
  Logger.log("Eureka!. A new row was inserted on the sheet named 'target. Lets do stuff");
  }
  else{
  Logger.log("Sigh. It either wasn't a new row AND/OR it wasn't on the sheet named 'target'. Either way, we can ignore it.");
  }

}