Search code examples
google-apps-scriptgoogle-sheets

Script error - TypeError: Cannot read properties of undefined


My current script will unlock a range of cells C8:D60. If this range is already unlocked, the script will cause an error message - TypeError: Cannot read properties of undefined (reading 'remove')

How do I test if range is unlocked first and prevent the error message? Thanks in advance!

function UnlockFriday() {
  var spreadsheet = SpreadsheetApp.openById('al;dskfjlasdjfl;asdfl;jkasf');
  spreadsheet.getRange('C8:D60').activate();
  var allProtections =     spreadsheet.getActiveSheet().getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var matchingProtections = allProtections.filter(function(existingProtection) {
  return existingProtection.getRange().getA1Notation() == 'C8:D60';
  });
  var protection = matchingProtections[0];
  protection.remove();
};

Solution

  • In the case of your showing script, how about the following modification?

    Modified script:

    function UnlockFriday() {
      var spreadsheet = SpreadsheetApp.openById('al;dskfjlasdjfl;asdfl;jkasf');
      spreadsheet.getRange('C8:D60').activate();
      var allProtections = spreadsheet.getActiveSheet().getProtections(SpreadsheetApp.ProtectionType.RANGE);
      var matchingProtections = allProtections.filter(function (existingProtection) {
        return existingProtection.getRange().getA1Notation() == 'C8:D60';
      });
    
      if (matchingProtections.length == 0) return; // Added
    
      var protection = matchingProtections[0];
      protection.remove();
    }
    
    • By this modification, when the length of matchingProtections is 0, the script is finished. By this, your error can be avoided.

    • As another approach, when find is used instead of filter, it becomes as follows.

      function UnlockFriday() {
        var spreadsheet = SpreadsheetApp.openById('al;dskfjlasdjfl;asdfl;jkasf');
        spreadsheet.getRange('C8:D60').activate();
        var allProtections = spreadsheet.getActiveSheet().getProtections(SpreadsheetApp.ProtectionType.RANGE);
        var matchingProtection = allProtections.find(existingProtection => existingProtection.getRange().getA1Notation() == 'C8:D60');
        if (!matchingProtection) return;
        matchingProtection.remove();
      }