Can I create google sheet tabs and also paste the format of a tab to them?

Viewed 32

I have the code to create tabs and the code to copy format however, I am looking for an integrations of these two. I want to create tabs given a specific list and then paste the format of a tab (called TEMPLATE) to the newly created tabs.

This is the Create Tabs code:

function createTabs() {
var ss = SpreadsheetApp.getActive()
ss.getSheetByName('Campaigns').getRange('A2:A40').getValues().filter(String)
    .forEach(function (sn) {
        if (!ss.getSheetByName(sn[0])) {
            ss.insertSheet(sn[0], ss.getSheets().length);}})}

This is the Paste Format code I found:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheets()[0];

var range = source.getRange("B2:D4");

// This copies the formatting in B2:D4 in the source sheet to
// D4:F6 in the sheet with gridId 1555299895. Note that you can get the gridId
// of a sheet by calling sheet.getSheetId() or range.getGridId().
range.copyFormatToRange(1555299895, 4, 6, 4, 6);
1 Answers

It looks like you are using insertSheet(sheetName, sheetIndex) to inset the new "tabs". You can use insertSheet(sheetName, sheetIndex, options) instead and set the template that way using {template: templateSheet} as the option. So you would only need the first half of your code, edited like below.

function createTabs() {
var ss = SpreadsheetApp.getActive()
ss.getSheetByName('Campaigns').getRange('A2:A40').getValues().filter(String)
    .forEach(function (sn) {
        if (!ss.getSheetByName(sn[0])) {
            ss.insertSheet(sn[0], ss.getSheets().length, {template: ss.getSheetByName('TEMPLATE')}})}
Related