最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Move to the next row when a sheet already exist - Stack Overflow

programmeradmin5浏览0评论

I'm a beginner when it comes to scripting and trying to work some things out to make it work correctly. So I have a sheet with Columns, Set Name, Number, URL. When I run a function I want it to create a new sheet for every row under the set name Column with the name in that cell. My problem is when I run this function if the sheet already it exist it stops the script how would I go about just moving on to the next row and creating that one if it doesn't exist.

This is my current code:

    function createNewSheetPerRow() {
  // Get the data from the sheet called CreateSheets
  var sheetNames =   SpreadsheetApp.getActive().getSheetByName("Set URL").getDataRange().getValues();

  // For each row in the sheet, insert a new sheet and rename it.
  sheetNames.forEach(function(row) {
    var sheetName = row[0];
    var sheet = SpreadsheetApp.getActive().insertSheet();
    sheet.setName(sheetName);
  });
}

I'm a beginner when it comes to scripting and trying to work some things out to make it work correctly. So I have a sheet with Columns, Set Name, Number, URL. When I run a function I want it to create a new sheet for every row under the set name Column with the name in that cell. My problem is when I run this function if the sheet already it exist it stops the script how would I go about just moving on to the next row and creating that one if it doesn't exist.

This is my current code:

    function createNewSheetPerRow() {
  // Get the data from the sheet called CreateSheets
  var sheetNames =   SpreadsheetApp.getActive().getSheetByName("Set URL").getDataRange().getValues();

  // For each row in the sheet, insert a new sheet and rename it.
  sheetNames.forEach(function(row) {
    var sheetName = row[0];
    var sheet = SpreadsheetApp.getActive().insertSheet();
    sheet.setName(sheetName);
  });
}
Share Improve this question edited Mar 22 at 14:13 Wicket 38.7k9 gold badges80 silver badges195 bronze badges asked Mar 22 at 8:45 Capt AwesomECapt AwesomE 111 bronze badge 3
  • 4 Just want to say it's a really really bad idea to create a new tab for every <whatever>. Best practice is to create 1 tab for input and another for output/dashboard with filters/slicers/query etc. – TheMaster Commented Mar 22 at 10:21
  • "I also...": The last statement of the original version of this question was making it too broad. On this site, questions should be about a specific problem that is unique to programming. – Wicket Commented Mar 22 at 14:11
  • From our standpoint the best solution is for you to learn the basics of Javascript and then come back and ask us scripting question rather than asking us to design your application for you. – Cooper Commented Mar 22 at 17:07
Add a comment  | 

2 Answers 2

Reset to default 2

Assuming that the sheet names are in column Sheet1!A2:A, you can read the names with Range.getDisplayValues() and ignore sheets that have already been added with try..catch, like this:

function createNewSheetPerRow() {
  const ss = SpreadsheetApp.getActive();
  ss.getRange('Sheet1!A2:A')
    .getDisplayValues()
    .flat()
    .filter(String)
    .forEach(sheetName => {
      try {
        ss.insertSheet(sheetName);
      } catch (error) {
        ; // ignore errors
      }
    });
}

See try..catch.

Use SpreadsheetApp.Spreadsheet.getSheets() to get all the sheets (SpreadsheetApp.Sheet) and use this to filter the list of sheets to be created.

Example

The below example is set to work on the active sheet. You might want to adapt the script to make work on a sheet based on their name or their ID. It also is set to grab the whole column A and assume that the first cell holds the column header / field name rather than a value, so it is removed by using Array.prototype.shift(). It uses other Arrays.prototype methods, specifically, filter, flat and includes.

/**
 * IMPORTANT
 *
 * Before running this function, ensure that the sheet with the list of names
 * is the active sheet.
 */
function addMissingSheets(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const currentNames = spreadsheet.getSheets().map(sheet => sheet.getName());
  // Array of the first column values, keeping out the empty strings of the blank
  // cells. Using method chaining to reduce the number of local variables
  const list = spreadsheet
    .getActiveSheet() 
    .getRange('A:A')  
    .getValues()      
    .filter(String) 
    .flat();
  list.shift(); // Removes the column header
  const missing = list.filter(name => !currentNames.includes(name));
  if(missing.length){
    Logger.log('%s new sheets will be inserted', missing.length);
    missing.forEach(name => spreadsheet.insertSheet(name));
  } else {
    console.log('There are no missing sheets');
  }
}

Please remember that, as of March 22, 2025, a spreadsheet in Google Sheets has a limit of 10 million cells. This will limit the number of sheets that your spreadsheet can have. Potentially, a spreadsheet can have many sheets, but too many might make it hard to use.

发布评论

评论列表(0)

  1. 暂无评论