GAS Spreadsheet avoid getting duplicates by marking as "SENT", not working?

时间:2015-10-30 21:51:02

标签: javascript arrays if-statement google-apps-script google-sheets

I have this script in Google Spreadsheet and it fetches all the rows marked "READY" just fine, then it sets the value in column "W"(23) to "SENT", and then I am trying to avoid fetching duplicates, by marking the column as "SENT" but then when I run the code again, it ignores the "SENT" that it just pasted? What is wrong here?

var ss = SpreadsheetApp.openById("12y85GmJ94s6k3213j2nGK8rFr0GOfd_Emfk8WHu_MUQ");
var stitchSheet = ss.getSheetByName("Sheet8");
var orderSheet = ss.getSheetByName("Sheet1");

var SENT = "SENT";

function getOrders() {

    var range  = orderSheet.getDataRange();
    var orders  = range.getValues();  

    for (var i = 1; i < orders.length; i++) {
        var row = orders[i];
        var status = row[1];
        var order = row[4]; 
        var name = row[5]; 
        var system = row[22]; 

        if(system != SENT){ 
            if(status.toString() === 'READY'){
                orderSheet.getRange(i,23).setValue(SENT);
                stitchSheet.appendRow([order,name]); 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的代码很好,因此某处必定存在逻辑错误。我注意到您在for循环var i中创建了1。我不知道这是否有意,但在大多数编程语言中,数组的索引几乎始终以0开头,这意味着您将从工作表的第2行开始,而不是从第1行开始。

查找逻辑错误

要查找逻辑错误,您需要了解如何在脚本编辑器中使用调试器控件。

在我用下面的星号标记的线上放置断点:

var ss = SpreadsheetApp.openById("12y85GmJ94s6k3213j2nGK8rFr0GOfd_Emfk8WHu_MUQ");
var stitchSheet = ss.getSheetByName("Sheet8");
var orderSheet = ss.getSheetByName("Sheet1");

var SENT = "SENT";

function getOrders() {

    var range  = orderSheet.getDataRange();
*   var orders  = range.getValues();  

    for (var i = 1; i < orders.length; i++) {
*       var row = orders[i];
        var status = row[1];
        var order = row[4]; 
        var name = row[5]; 
*       var system = row[22]; 

        if(system != SENT){ 
            if(status.toString() === 'READY'){
                orderSheet.getRange(i,23).setValue(SENT);
                stitchSheet.appendRow([order,name]); 
            }
        }
    }
}

启动调试器,它将在第一个断点处停止。检查range的值。展开This会让您找到orderSheetSENT(因为它们不在函数范围内,应该在范围内)。如果没有,你在这里遇到了问题。

转到下一个断点并检查orders,它现在应该有一个数组数组。您可以检查您是否拥有正确的值,如果没有,请跳到下一个断点并查看row是什么。