Adithya Shreshti
Adithya Shreshti

Reputation: 55

How to directly open the new google sheet created from script?

I have been using the following code (after some edits and help from the community here) to create a duplicate sheet from a template sheet. However, the number of sheets have increased now. Is there a way to make some edits in this code such that the newly created sheet shows up directly so I can right away edit without horizontally scrolling through to find the new sheet that was created from the script? .

Edited question for giving better clarity on the issue.

function duplicateSheetWithProtections() {
      var ui = SpreadsheetApp.getUi();
      var oldSheetName = ui.prompt('Sheet to Copy?');
      var newSheetName = ui.prompt('New Sheet Name?');
      var ss = SpreadsheetApp.getActiveSpreadsheet(); 
      sheet = ss.getSheetByName(oldSheetName.getResponseText());
      sheet2 = sheet.copyTo(ss).setName(newSheetName.getResponseText()); 
      var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
      for (var i = 0; i < protections.length; i++) {
        var p = protections[i];
        var rangeNotation = p.getRange().getA1Notation();
        var p2 = sheet2.getRange(rangeNotation).protect();
        p2.setDescription(p.getDescription());
        p2.setWarningOnly(p.isWarningOnly());
        if (!p.isWarningOnly()) {
          p2.removeEditors(p2.getEditors());
          p2.addEditors(p.getEditors());
          // p2.setDomainEdit(p.canDomainEdit()); //  only if using an Apps domain 
    
            /* Make the new sheet active */
      ss.setActiveSheet(sheet);
       }
      }
    }

Upvotes: 1

Views: 50

Answers (1)

Mike Steelson
Mike Steelson

Reputation: 15328

Try

sheet2.moveActiveSheet(0)

this will be the simplest and most effective solution

Upvotes: 2

Related Questions