如何使用宏移至下一个范围?

时间:2019-04-20 12:45:26

标签: google-apps-script google-sheets google-apps google-sheets-macros

我有一个从录制中得到的示例宏代码。因此,每当我运行它时,该代码就会保护“ C”和“ D”列。

但是,我想要的是当我第二次运行此代码时,它保护接下来的两列,即'E'和'F',依此类推。

我该怎么做??

此外,有没有一种方法可以使这段代码每天在一天的固定时间自动运行一个月,所以我不必每天手动运行该代码。

/** @OnlyCurrentDoc */

function DataReWriteProtection() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('C:D').activate();
  var protection = spreadsheet.getRange('C:D').protect();
};

1 个答案:

答案 0 :(得分:0)

此代码可以为您提供开发自己的代码的开始。

该脚本应作为可安装,时间驱动,触发器安装。您应该选择最适合您的频率和执行时间。

function so5577363801() {

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

  // assumes that cell A1 contains the column value (as an integer) for the next column to be protected
  // assumes that two columns (side-by-side) are to be protected
  var colNumRange = sheet.getRange("A1");
  var colNum = colNumRange.getValue();
  var startcol = colNum;
  var endcol = colNum+1;

  // convert column numbers to letters
  var startletter = columnToLetter(startcol);
  var endletter = columnToLetter(endcol);
  // Logger.log("DEBUG: Cell A1: "+colNum+", start column: "+startcol+", endcol: "+endcol+", start letter: "+startletter+", end letter: "+endletter);//DEBUG

  // define the range to be protected
  var range = sheet.getRange(startletter+":"+endletter);
  // Logger.log("DEBUG: range = "+range.getA1Notation());//DEBUG
  var rangename = '"'+startletter+":"+endletter+'"';
  //Logger.log("DEBUG: range name: "+rangename);//DEBUG

  // protect the range, and assign a description
  var protection = sheet.getRange(startletter+":"+endletter).protect();
  protection.setDescription(rangename).setWarningOnly(true);

  // update CellA1 with the column number to be used next time.
  var newcol = colNum+2;
  colNumRange.setValue(newcol); 
}

function columnToLetter(column){
  var temp, letter = '';
  while (column > 0){
    temp = (column - 1) % 26;
    letter = String.fromCharCode(temp + 65) + letter;
    column = (column - temp - 1) / 26;
  }
  return letter;
}