[英]Automatically create a new sheet with data of a row in the mastersheet
Consider I have a mastersheet with names in column A and a link in colum B, starting in row 2.考虑我有一个母版表,其中 A 列中的名称和 B 列中的链接,从第 2 行开始。
The code below, for a reason I don't understand, creates only one new sheet with the name in row 2, and sets the value of the row 3 in the newly created sheet.下面的代码,出于我不明白的原因,只在第 2 行创建了一个名称为的新工作表,并在新创建的工作表中设置了第 3 行的值。
I'd like that to work as followed:我希望它按以下方式工作:
Can someone help me figure out what's going on?有人可以帮我弄清楚发生了什么吗? I read the documentation about loops and getRange but I can't figure it out..
我阅读了有关循环和 getRange 的文档,但我无法弄清楚..
Thank you very much非常感谢
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)
}
}
I believe your goal as follows.我相信你的目标如下。
In your script,在你的脚本中,
var sheet = dataSheet.getSheetByName(swimmerName)
, swimmerName
is not declaread.var sheet = dataSheet.getSheetByName(swimmerName)
, swimmerName
未声明。
swimmerName
is not declared elsewhere, an error occurs at this line.swimmerName
时,此行会发生错误。var col = values[i]
, i
is not declared.var col = values[i]
处,未声明i
。1
.1
。 From getRange('A2:B')
, in this case, the values are retrieved from 3rd row.getRange('A2:B')
开始,在这种情况下,值是从第 3 行检索的。swimmerName
and col
are not changed. swimmerName
和col
没有改变。 In order to achieve your goal, I would like to propose the following flow.为了实现您的目标,我想提出以下流程。
When above flow is reflected to a script, it becomes as follows.当上述流程反映到脚本时,它变成如下。
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
is growing in the loop and that is used for checking the duplicate sheet names.sheetNames
在循环中增长,用于检查重复的工作表名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.