Just
Just

Reputation: 437

How do I delete a sheet/tab in a Google spreadsheet pragmatically using GAS/Javascript

I have a code that dynamically creates new sheets based on the first-row value in the main sheet.

I would like to have the code to check the existence of the sheet name and overwrite the sheet or delete it first if it exists and then creates it afresh from the new data in main sheet.

I will appreciate your help in restructuring.

function newSheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var templateSheet = ss.getActiveSheet();
    var sheet1 = ss.getSheetByName("main")
    var getNames = [...new Set(sheet1.getRange("A2:A").getValues().filter(String).toString().split(","))];

    for (var i = 0; i < getNames.length; i++) {
        var copy = ss.getSheetByName(getNames[i]);


       if (copy) {  // This is where I am kind lost on how to structure it.

        // if a copy exists delete or overwrite existing sheet here

        } else {

           var rowIndexes = sheet1.getRange("A:A").getValues()
                .map((value, index) => [value[0], (index + 1)])
                .filter(value => value[0] === getNames[i]);


            var namedSheet = ss.insertSheet(getNames[i]);
            rowIndexes.map(index => {
                var rowValues = sheet1.getRange(index[1], 1, 1, sheet1.getLastColumn()).getValues();
                namedSheet.appendRow(rowValues[0]);
            });

            ss.setActiveSheet(ss.getSheetByName(getNames[i]));
            ss.moveActiveSheet(ss.getNumSheets());
        }
    }
}

Upvotes: 0

Views: 1023

Answers (1)

Nerdy Sid
Nerdy Sid

Reputation: 332

I think there are multiple ways to achieve the solutions you are looking for

First:

Yes, you can replace it.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.setName("not first anymore");

So in your case,

var copy = ss.getSheetByName(getNames[i]);

if (copy) {  // This is where I am kind lost on how to structure it.

 copy.setName("New name")
 // if a copy exists delete or overwrite existing sheet here

 }

Second: Yes, you can delete the sheet as well.

// The code below deletes the specified sheet.
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('My Sheet');
ss.deleteSheet(sheet);

So in your case,

 if (copy) {  // This is where I am kind lost on how to structure it.

 ss.deleteSheet(copy)
 // if a copy exists delete or overwrite existing sheet here

 }

Sorry if I have misunderstood your problem.

Upvotes: 3

Related Questions