【发布时间】:2020-11-01 17:14:12
【问题描述】:
我正在将一张数据分成多张,使用电子邮件地址作为唯一标识符。
我正在使用我找到并编辑的某些脚本的变体,但使用的是 copyTo 而不是 appendRow。
问题在于它似乎将特定数据集的最后一行复制到后续工作表中。
我认为这可能是因为我使用的是 getActiveSheet 而不是明确定位正确的工作表,所以我尝试这样做,使用类似:getSheetByName(emailAddress[i][0])。
但是,这不断出现空值。当我记录 emailaddress 的值时,查看记录器,这些值显示正确,所以不太清楚为什么我得到 null。
以下是“有效”的脚本,但会将最后一行复制到后续工作表。
function myFunction() {
var theWorkbook = SpreadsheetApp.getActiveSpreadsheet();
var theSheet = theWorkbook.getSheetByName("Copied");
// This var will contain all the values from column B -> The email addresses
var theEmails = theSheet.getRange("B:B").getValues();
// This var will contain all the rows
var rows = theSheet.getDataRange().getValues();
//Set the first row as the header
var header = rows[0];
//Store the Sheets already created
var completedSheets = []
//The last created Sheet
var last = theEmails[1][0]
for (var i = 1; i < theEmails.length; i++) {
//Check if the Sheet is already done, if not create the sheet
if(!completedSheets.includes(theEmails[i][0])) {
//Set the Sheet name = email address (except if there is no name, then = Blank)
if (theEmails[i][0] === "") {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("Blank");
} else {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(theEmails[i][0]);
}
//append the header
currentSheet.appendRow(header);
var rowtocopy = theSheet.getRange(i,1,1,8);
rowtocopy.copyTo(currentSheet.getRange(currentSheet.getLastRow()+1, 1));
completedSheets.push(theEmails[i][0])
last = theEmails[i][0]
} else if (last == theEmails[i][0]) {
// If the sheet is created append the row to the sheet
var currentSheet = SpreadsheetApp.getActiveSpreadsheet();
var activespreadsheet = SpreadsheetApp.getActiveSheet();
var rowtocopy = theSheet.getRange(i,1,1,8);
rowtocopy.copyTo(activespreadsheet.getRange(activespreadsheet.getLastRow()+1, 1));
}
}
}
还有我试图命名工作表的代码 sn-pt(以及它的许多变体),尽管这会返回 null 错误。
else if (last == theEmails[i][0]) {
// If the sheet is created append the row to the sheet
var currentSheet = SpreadsheetApp.getActiveSpreadsheet();
var activespreadsheet =SpreadsheetApp.getActive().getSheetByName(last);
var rowtocopy = theSheet.getRange(i,1,1,8);
rowtocopy.copyTo(activespreadsheet.getRange(activespreadsheet.getLastRow()+1, 1));
我做错了什么?
【问题讨论】:
标签: google-apps-script google-sheets copyto