我试图遍历一系列数据,在数据的第一列中查找某个值,然后将具有该值的所有行复制到另一个名为“ Closed Requests”的工作表中。
function copyToClosed(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Open Requests");
var range = sheet.getActiveCell();
var lastrow = sheet.getLastRow();
var datarange = sheet.getRange(10,2,lastrow-1, 50).getValues();
var row = 10;
var x = [];
var sheetNameToMoveTheRowTo = "Closed Requests"
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
for (i=0;i<datarange.length;i++) {
if(i[0] == "CC") {
x.push([datarange[i]])
}
var targetRange =
targetSheet.getRange
(targetSheet.getLastRow()+1,2,datarange.length,datarange[0].length)
targetRange.setValues(x)
}
}
如您所见,我首先定义数据范围并创建一个数组“ x”。然后,我遍历数据以在范围的第一列中找到文本“ CC”。然后,将这些行推送到数组中,然后使用.setValues()将它们复制到工作表“ Closed Requests”上。我在.setValues()处收到错误消息
浏览该错误的其他情况,我发现数组的尺寸一定存在问题,并且我错误地定义了数组或范围。但是,我无法弄清楚到底是什么问题。
任何帮助将不胜感激。
答案 0 :(得分:1)
错误在for循环中。试试这个:
function copyToClosed(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Open Requests");
var range = sheet.getActiveCell();
var lastrow = sheet.getLastRow();
var datarange = sheet.getRange(10,2,lastrow-1, 50).getValues();
var row = 10;
var x = [];
var sheetNameToMoveTheRowTo = "Closed Requests"
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
for (i=0;i<datarange.length;i++) {
if(datarange[i][0] == "CC") {
x.push(datarange[i])
}}
targetSheet.getRange(targetSheet.getLastRow()+1,2,x.length,x[0].length).setValues(x)
}
答案 1 :(得分:0)
另一个可行的选择是,您可以将其运行在onEdit上,因此当值更改为CC时,它将自动移动该行。您可以使用以下代码来实现
function onEdit(event) {
// assumes source data in sheet named Active
// target sheet of move to named Found
// test column with yes/no is col 13 or M
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(s.getName() == "Open Requests" && r.getColumn() == 1 && r.getValue() == 'CC') {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Closed Requests");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).moveTo(target);
s.deleteRow(row);
}
}