I am attempting to find certain values in a datasheet using a for loop, and based on whether the value is = "Yes" it will move the row to another sheet. The loop should further look for the value of requesttype (in this case SRM, CC, or TM1) and move only certain parts of the row to the other sheet.
Hence, the for loop should copy the row based on inputs from two different columns in the data sheet: "All Outputs"
So while my code works in general when I run it, it only seems to execute the function for half of the rows where "Yes"is entered.
Each time I run the script half of the rows that should be moved, get moved but the other half stays in the original sheet. I can run the code until there is only one row left, in which case nothing happens anymore.
Here is what I have:
function myonEdit2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
var sheetNameToWatch = "Open Requests";
var columnNumberToWatch = 38;
var watchColumn = 2;
var valueToWatch = "Yes";
var datarange = sheet.getRange(9, 2, 900, 36).getValues();
var sheetNameToMoveTheRowTo = "Closed Requests"
for (i = 0; i < datarange.length -1; i++) {
if (datarange[i][35] == "Yes") {
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
if (datarange[i][0] == "SRM") {
var targetRange3 = targetSheet.getRange(targetSheet.getLastRow() + 1, 2);
sheet.getRange(i, 2, 1, 8).moveTo(targetRange3);
sheet.deleteRow(rowstart + i);
}
else if (datarange[i][0] == "GC") {
var targetRange3 = targetSheet.getRange(targetSheet.getLastRow() + 1, 2);
sheet.getRange(i, 2, 1, 8).moveTo(targetRange3);
sheet.deleteRow(i);
}
else if (datarange[i][0] == "TM1") {
var targetRange4 = targetSheet.getRange(targetSheet.getLastRow() + 1, 2, 1, 6);
sheet.getRange(i, 2, 1, 6).moveTo(targetRange4);
var targetRange5 = targetSheet.getRange(targetSheet.getLastRow(), 10, 1, 1)
sheet.getRange(i, 13, 1, 1).copyTo(targetRange5)
sheet.deleteRow(i);
}
}
}
As I said the code works fine but it does not execute for all the rows it should execute for.
As you can see from above, I define the for loop range as the complete datasheet in which the table is in. Then I create the first (main) if condition namely the 36th column of the data range being "Yes". This should define for which rows the script will be executed.
The second if condition defines which exact columns of the row should be copied and depends on whether the first column is = SRM, CC or TM1.
If anybody could help me figure out why the code does not execute for all rows that would be great.
for (i = lastrow; i>9,i--)
However, when I run it, it still does the same as before even if I try to run only the delete row part. - Fabian KrausArray
element indices, andRange
row and column numbers - tehhowch