简体   繁体   English

如何使用 Google 表格中的 Google Apps 脚本从一个范围内创建多个选项卡?

[英]How can multiple tabs be created from a range using Google Apps Script in a Google Sheet?

I need to create a custom function to create multiple tabs in a Google Sheet based on the values in column A. How do I do this?我需要创建一个自定义 function 以根据 A 列中的值在 Google 表格中创建多个选项卡。我该怎么做?

This is for tracking the data on particular e-commerce products.这是为了跟踪特定电子商务产品的数据。 The name of them are in the first column of the first tab.它们的名称位于第一个选项卡的第一列中。 Each entry in column A needs to have a tab labeled as the same name. A 列中的每个条目都需要有一个标记为相同名称的选项卡。

I don't know how to do this.我不知道该怎么做。

The output should be new tabs created labeled by each cell in column A. output 应该是由 A 列中的每个单元格标记的新选项卡。

Copy and paste this code in the script editor.将此代码复制并粘贴到脚本编辑器中。

function createSheet(sheetIndex, value){
  // Check if cell is empty after editing
  if (value.oldValue){
    value = 'Sheet' + (sheets.length - sheetIndex);
  }

  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  // If sheet already exits just change the sheet name
  if (sheets[sheetIndex]) {
    sheets[sheets.length - sheetIndex].setName(value)
  } else {
    SpreadsheetApp.getActiveSpreadsheet().insertSheet(value);
  }
}

function onEdit(e) {
  var sheet = e.source.getActiveSheet();
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  // Check if the sheet being edited is the first sheet and first column (A)
  if (sheet.getSheetId() == sheets[0].getSheetId() && sheet.getActiveCell().getColumn() == 1) {
    createSheet(e.range.getRowIndex(), e.value)
  }

}

You can extend the code to support deletion;可以扩展代码支持删除; it's a bit tricky though because there is no onDelete event.这有点棘手,因为没有 onDelete 事件。 You can compare the sheets array with the values in the column to determine which sheet delete.您可以将工作表数组与列中的值进行比较,以确定删除哪个工作表。

Creating Multiple Sheets with Templates and Position使用模板和 Position 创建多个工作表

  1. Open a new Spreadsheet and go to script editor打开一个新的电子表格和 go 到脚本编辑器
  2. Load the Code and Save it加载代码并保存
  3. Create the sheet named "Sheet Data"创建名为“Sheet Data”的工作表
  4. Create the three templates创建三个模板
  5. Run createTrigger()运行 createTrigger()
  6. Close the Spreadsheet关闭电子表格
  7. Open the Spreadsheet give it some time and it will create all of the sheets without bothering the templates or the Sheet Data sheet.打开电子表格给它一些时间,它将创建所有工作表,而不会打扰模板或工作表数据表。 The Code:编码:
    function onOpen() {
      SpreadsheetApp.getUi().createMenu("My Menu")
      .addItem('Create onOpen Trigger', 'createTrigger')
      .addToUi();
    }
    //This is where the sheets get created  
    function startUp() {
      var ss=SpreadsheetApp.getActive();
      var templateA=["A","B","C"];
      templateA.forEach(function(name){ss.getSheetByName(name).hideSheet();});
      var sh=ss.getSheetByName("Sheet Data");
      var shts=ss.getSheets();
      var shtnames=shts.map(function(sh){if(!sh.isSheetHidden()){return sh.getName();}}).filter(function(e){return e});
      var hdnshts=shts.map(function(sh){if(sh.isSheetHidden()){return sh.getName();}}).filter(function(e){return e});
      var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
      var vA=rg.getValues();
      vA.sort(function(a,b){return a[2]-b[2];});
      vA.forEach(function(r){
        if(shtnames.indexOf(r[0])==-1 && r[0]!=sh.getName()) {
          ss.insertSheet(r[0], r[2], {template:ss.getSheetByName(r[1])});
        }
        shts=ss.getSheets();
        shtnames=shts.map(function(sh){if(!sh.isSheetHidden()){return sh.getName();}}).filter(function(e){return e});
      });
      var end="is near";
    }

    function isTrigger(funcName){
      var r=false;
      if(funcName){
        var allTriggers=ScriptApp.getProjectTriggers();
        for(var i=0;i<allTriggers.length;i++){
          if(funcName==allTriggers[i].getHandlerFunction()){
            r=true;
            break;
          }
        }
      }
      return r;
    }

    //Installable onOpen trigger
    //run this function first
    function createTrigger() {
      var ss=SpreadsheetApp.getActive();
      if(!isTrigger('startUp')) {//This keeps you from creating unnecessary triggers
        ScriptApp.newTrigger('startUp').forSpreadsheet(ss).onOpen().create()
      }
    }

    //This is useful for testing
    function deleteSheets() {
      var ss=SpreadsheetApp.getActive();
      var sh=ss.getSheetByName("Sheet Data");
      var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
      var vA=rg.getValues();
      vA.forEach(function(r){
        ss.deleteSheet(ss.getSheetByName(r[0]));
      });
    }

The Creation Sheet:创作表:

在此处输入图像描述

Three Templates: I just made these templates up as simple examples to assist in the creation of your sheets.三个模板:我只是将这些模板制作为简单的示例,以帮助您创建工作表。 I find that non programmers really excel at this process making extremely fancy spreadsheets.我发现非程序员在这个过程中真的是 excel 制作非常精美的电子表格。 For me, I keep them simple.对我来说,我让它们保持简单。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

I tried using this gif to show how the files are create with the spreadsheet opens up the first time.我尝试使用此 gif 来展示如何在第一次打开电子表格时创建文件。 It won't create additional sheets of the same name.它不会创建其他同名工作表。 But if you add additional names it will create them.但是,如果您添加其他名称,它将创建它们。 It's not capable of deleting sheet names that have been removed, so there's something you can do for yourself.它无法删除已删除的工作表名称,因此您可以为自己做一些事情。

在此处输入图像描述

This function below creates a new sheet every time a cell from column A in your original sheet is edited, only if another sheet with this name does not exist already.每次编辑原始工作表中 A 列中的单元格时,下面的 function 都会创建一个新工作表,前提是不存在具有此名称的另一个工作表。 To accomplish that, and onEdit trigger is used, as well as the corresponding event object :为此,使用了onEdit触发器以及相应的事件 object

function onEdit(e) {
  var firstSheetName = "Sheet1"; // Name of your original sheet, change accordingly
  var range = e.range; // Edited cell
  var ss = e.source; // Edited spreadsheet
  var sheetName = range.getSheet().getName(); // Name of edited sheet
  var value = range.getValue(); // Value of the edited cell
  // Checks whether edited sheet is the original one, and edited column is A:
  if(sheetName == firstSheetName && range.getColumn() == 1) {
    // Checks whether a sheet with this name exists:
    var sheetExists = ss.getSheets().some(function(sheet) {
      return sheet.getName() == value;
    });
    // Create new sheet only if a sheet with this name it doesn't exist:
    if(!sheetExists) { 
      ss.insertSheet(value);
      range.activate(); // Go back to original edited cell
    }
  }
}
  • See the comments in the shared script to understand what the code is doing, step by step.请参阅共享脚本中的注释,逐步了解代码在做什么。
  • In this example, the original sheet is called "Sheet1".在此示例中,原始工作表称为“Sheet1”。 Change it accordingly if that's not your case.如果不是您的情况,请相应地更改它。

I hope this is of any help.我希望这有任何帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Google Apps Script 在来自 Google 表格的多行中拆分 Google 幻灯片表中的数据(基于字符限制)? - How to split data in a Google Slides Table (based on character limit) in multiple rows coming in from a Google Sheet using Google Apps Script? 如何使用 Google Apps 脚本将公式()设置为范围? - How to setFormulas() to a range using Google Apps Script? 从Google Apps脚本查询Google表格 - Query a Google Sheet from Google Apps Script 如何使用 Google Sheet Script 将数据范围从一个工作表复制到另一个工作表 - How to Copy a data range from one sheet to another sheet using Google Sheet Script 使用 Google Apps 脚本,如何替换 Google 表格模板中的文本以制作新表格? - Using Google Apps Script, how can I replace text in a Google Sheets template to make a new Sheet? 如何通过谷歌应用程序脚本从 xlsx gmail 附件中提取谷歌表格中的信息 - How can I extract Information in a Google Sheet from a xlsx gmail attachment via google apps script Google Spreadsheet:如何使用Google Apps脚本命名范围 - Google Spreadsheet: How to name a range using Google Apps Script 如何使用 Google 脚本从 1 个 Google 工作表中复制特定值并粘贴到另一个工作表? - How can I copy specific values from 1 Google Sheet and paste to another Sheet using Google Script? Google Sheet Script - 根据包含电子邮件的一系列单元格隐藏选项卡 - Google Sheet Script - Hiding tabs based on a range of cells containing emails Google Apps 脚本将特定范围从任何选项卡复制到主工作表 - Google Apps Script Copying Specific Range from any tab to a Master Sheet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM