检查 Google 表格单元格是否受 Google Apps 脚本保护

问题描述 投票:0回答:1

如何检查 Google 表格中的单元格是否受到 Google Apps 脚本的保护?具体来说,范围保护,而不是工作表保护。

google-apps-script google-sheets protection spreadsheet-protection
1个回答
1
投票

检查坐标为

row
col
(从1开始)的单元格是否有保护使用:

function has_protection(row,col) { // row and column starting from 1
  var sheet = SpreadsheetApp.getActiveSheet();
  var cell_has_protection = false;      
  var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE); // get all protected ranges
  if ( protections != '' ) {
    for (var p = 0; p < protections.length; p++) {
      var pro_range = protections[p].getRange(); // each protected range
      if (row >= pro_range.getRow()
      && row <= (pro_range.getRow() + pro_range.getHeight() - 1)
      && col >= pro_range.getColumn()
      && col <= (pro_range.getColumn() + pro_range.getWidth() - 1)) {
        cell_has_protection = true;
      } 

    }
  }
  return cell_has_protection;
}

您还可以使用以下代码突出显示工作表上所有受保护的单元格(它将清除工作表上的所有其他突出显示并仅填充受保护的单元格):

function color_protected(){
  var sheet = SpreadsheetApp.getActiveSheet();      
  var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  if ( protections != '' ) {
    sheet.getRange('1:' + sheet.getMaxRows()).setBackground(null); // clear all background on the sheet
    for (var p = 0; p < protections.length; p++) {
      var pro_range = protections[p].getRange();
      //Logger.log(pro_range.getA1Notation());
      pro_range.setBackground('#fbbc04'); // color protected range
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.