Monday, 15 April 2019

Search for and remove protected named ranges

Following on from this blog post to search for protected named ranges, we now look towards removing said protection once we have found it. The following Google Apps Script is designed to loop through the protection in a spreadsheet and find a name match with a specific one we are targeting, then remove the protection.

The below line gets an array of objects representing all protected ranges in the spreadsheet:
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
As we loop through getting the name of each named range from the above array (see previous blog post), we perform an additional if check to look for a specific name (studentDetails in this example):
if (name == 'studentDetails') {
      protections[i].remove();
      break;
    }
Upon finding the matching name we 'remove' the protection and 'break' out of the loop (as we no longer need to keep looping through the other names).


Search for and remove protected named ranges.xlsx

2 comments:

  1. I can't get the name of the ranges, see below. Coold you please give me a help?

    function searchAndRemove() {

    var ss = SpreadsheetApp.getActive().getSheetByName('Requerimento');

    /*
    Get an array of objects representing all protected RANGEs in the spreadsheet.
    If looking for sheet protection would use: (SpreadsheetApp.ProtectionType.SHEET)[0]
    */
    var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);

    // loop through protections array *************************
    for (var i=0; i<protections.length; i++) {

    // get the name of each named range
    var name = protections[i].getRangeName();
    Logger.log('Named range is: ' + name);

    // look for name match and remove protected named range
    if (name == 'studentDetails') {
    protections[i].remove();
    break;
    }

    }


    [20-03-30 23:18:18:498 BRT] Named range is: null
    [20-03-30 23:18:18:501 BRT] Named range is: null
    [20-03-30 23:18:18:503 BRT] Named range is: null
    [20-03-30 23:18:18:506 BRT] Named range is: null
    [20-03-30 23:18:18:508 BRT] Named range is: null
    [20-03-30 23:18:18:510 BRT] Named range is: null
    [20-03-30 23:18:18:512 BRT] Named range is: null

    ReplyDelete
    Replies
    1. Hi

      Have you created a 'Named range' prior to implementing this script? The above blog post follows on from here where you need to create a 'Named range' called 'studentDetails': https://www.pbainbridge.co.uk/2019/04/protect-named-range-in-google-sheet.html

      Thanks

      Delete