如何运行多个脚本?

时间:2019-01-08 05:30:16

标签: google-apps-script

有人可以帮我吗? 我希望所有这些都能正常工作,但只有第一个有效。

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mysheet = ss.getSheetByName("Sheet1");
  var activeCell = ss.getActiveCell().getA1Notation();

  if( activeCell == "A1" )
  {
    for(var i=0;i<50;i++)
    {
      if( i%2 == 0 )
        mysheet.getRange("A1:M1").setBackground("RED");
      else
        mysheet.getRange("A1:M1").setBackground("WHITE");

      SpreadsheetApp.flush();
      Utilities.sleep(500);
    }
  }
}


function onEdit1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mysheet = ss.getSheetByName("Sheet1");
  var activeCell = ss.getActiveCell().getA1Notation();

  if( activeCell == "A2" )
  {
    for(var i=0;i<50;i++)
    {
      if( i%2 == 0 )
        mysheet.getRange("A2:M2").setBackground("RED");
      else
        mysheet.getRange("A2:M2").setBackground("WHITE");

      SpreadsheetApp.flush();
      Utilities.sleep(500);
    }
  }
}

function onEdit2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mysheet = ss.getSheetByName("Sheet1");
  var activeCell = ss.getActiveCell().getA1Notation();

  if( activeCell == "A3" )
  {
    for(var i=0;i<50;i++)
    {
      if( i%2 == 0 )
        mysheet.getRange("A3:M3").setBackground("RED");
      else
        mysheet.getRange("A3:M3").setBackground("WHITE");

      SpreadsheetApp.flush();
      Utilities.sleep(500);
    }
  }
}

我希望其中的3个闪烁

1 个答案:

答案 0 :(得分:0)

如果您希望所有三个功能都在编辑时运行,请从一个功能中全部调用它们。

onEdit() {
    function1();
    function2();
    function3();
}

function1() {
    // Do something
}

function2() {
    // Do something
}

function3() {
    // Do something
}

编辑

这三种方法都更短了:

function onEdit() {

    var spreadsheet = SpreadsheetApp.getActive();
    var sheet = spreadsheet.getActiveSheet();
    var cell = spreadsheet.getActiveCell();

    var col = cell.getColumn();
    var row = cell.getRow();

    if (col === 1 && sheet.getName() === 'Sheet1') {
    // If the edited cell is in column A (1) and on the correct sheet

        for (var num = 0; num < 50; num++) {

            var colour = num%2 === 0
                ? 'RED'
                : 'WHITE';
            // Using ? and : like this is called a ternary operation. It's a
            // shorter form of if. ifStatement ? true : false.

            sheet.getRange('A' + row + ':M' + row).setBackground(colour);
            // Get the range for the edited row and set the bg colour

            SpreadsheetApp.flush();
            Utilities.sleep(500);
        }
    }
}