簡體   English   中英

使用主表中的一行數據自動創建一個新表

[英]Automatically create a new sheet with data of a row in the mastersheet

考慮我有一個母版表,其中 A 列中的名稱和 B 列中的鏈接,從第 2 行開始。

下面的代碼,出於我不明白的原因,只在第 2 行創建了一個名稱為的新工作表,並在新創建的工作表中設置了第 3 行的值。

我希望它按以下方式工作:

  • 創建一個名為 col A 的工作表
  • 在新創建的工作表中設置 col A 和 col B 的值

有人可以幫我弄清楚發生了什么嗎? 我閱讀了有關循環和 getRange 的文檔,但我無法弄清楚..

非常感謝

function createNewSheets() {
  var dataSheet = SpreadsheetApp.getActiveSpreadsheet();
  var values = dataSheet.getSheetByName('mastersheet').getRange('A2:B').getValues();
  
  // Get sheet with current swimmer name:
  var sheet = dataSheet.getSheetByName(swimmerName);

  var col = values[i]; // Current row
  var swimmerName = col[0]; // swimmer name

  // Iterate through all rows of data from "mastersheet":
  for (var i = 1; i < values.length; i++) {

    // Check if sheet with current swimmer name exists. If it doesn't it creates it:
    if (!sheet) {
      sheet = dataSheet.insertSheet(swimmerName);
    }
    
    // Sets current row of data to the new sheet:
    sheet.getRange(1, 1, col.length, col[0].length).setValues(col)
  }
}

我相信你的目標如下。

  • 您想從“mastersheet”表中的“A”和“B”列中檢索值。
  • 您想使用從“mastersheet”工作表中檢索到的“A”列的值作為工作表名稱。
  • 當檢索到的工作表名稱的工作表在活動電子表格中不存在時,您希望插入具有工作表名稱的新工作表。
  • 插入新工作表時,您希望將工作表名稱的同一行復制到插入的工作表中。
  • 您想使用 Google Apps 腳本實現此目的。

修改點:

  • 在你的腳本中,

    • var sheet = dataSheet.getSheetByName(swimmerName)swimmerName未聲明。
      • 當在其他地方沒有聲明swimmerName時,此行會發生錯誤。
    • var col = values[i]處,未聲明i
    • 在 for 循環中,
      • 第一個索引是1 getRange('A2:B')開始,在這種情況下,值是從第 3 行檢索的。
      • swimmerNamecol沒有改變。
  • 為了實現您的目標,我想提出以下流程。

    1. 檢索當前工作表名稱。
    2. 從“mastersheet”表中檢索值。
    3. 使用檢索到的工作表名稱和值,插入新工作表並放置值。

當上述流程反映到腳本時,它變成如下。

示例腳本:

function createNewSheets() {
  // 1. Retrieve the current sheet names.
  var dataSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheetNames = dataSheet.getSheets().map(s => s.getSheetName());

  // 2. Retrieve the values from "mastersheet" sheet.
  var masterSheet = dataSheet.getSheetByName('mastersheet');
  var values = masterSheet.getRange('A2:B' + masterSheet.getLastRow()).getValues();

  // 3. Using the retrieved sheet names and values, the new sheets are inserted and the values are put.
  values.forEach(r => {
    if (!sheetNames.includes(r[0])) {
      dataSheet.insertSheet(r[0]).appendRow(r);
      sheetNames.push(r[0]);
    }
  });
}
  • 在此示例腳本中, sheetNames在循環中增長,用於檢查重復的工作表名稱。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM