【问题标题】:Google Sheet Script - Why is this loop not working?Google Sheet Script - 为什么这个循环不起作用?
【发布时间】:2018-02-01 10:28:01
【问题描述】:

我正在 Google Script 中执行我的第一个循环,但它无法正常工作。它只工作了一半,所以我不知道是什么问题。

代码应该在每一行和第 1 列中循环并输入下一个 ID 号(一旦完成,它应该将 LastID 号加 1,然后将其放在下一行)。

问题在于它在每个单元格中输入 LastID,然后最后将 LastID 增加 1(假设 LastID 为 1,它将 1 放入所有单元格中,而不是 2、3、4等等。)

(注意我遗漏了一些声明工作表变量等的代码。)

function myFunction() {
    var IDCount = 1;
    var LastID = 1;
    var RowCount = 4;

    {
        for (var x = IDCount; x < RowCount; x++)
            Browser.Buttons.YES_NO);

    sheet.getRange((x + 2), 1).setValue(LastID) //set next row with missing ID number

    sheet.getRange(2, 7).setValue(LastID) //set the new ID
    LastID++ //Increase LastID by 1

}
}

希望有人能提供帮助。谢谢

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    你还没有定义循环体。如果我们不提供大括号,默认情况下假定正文中只有一行。所以在你的情况下,这正在发生。它只是假设

    sheet.getRange((x+2), 1).setValue(LastID) //set next row with missing ID number

    在循环内,因此它为所有行设置相同的值。

    试试这个代码:

    function myFunction() {
        var startRow = 1; // You can set your start row number here
        var startId = 1; // You can set your start id number here
        var lastRow = 4; // You can set your last row number here, till where you want to set id;
        //if you want this to be last row of sheet then = sheet.getLastRow();
        var tempId = startId;
        for (var x = startRow; x <= lastRow; x++) {
            sheet.getRange(x, 1).setValue(tempId) //set the ID number
            tempId++; // Increment the ID by 1
        }
    }
    

    【讨论】:

    • 完美(并且解释清楚)。现在工作得很好。非常感谢你的帮助。约翰
    • 请问有没有办法将其标记为已解决?
    • 接受作为解决方案/支持您可以/[我认为应该按照堆栈溢出礼仪]接受它作为接受的答案和/支持。这样之后会来到这个屏幕的人可以区分这个答案并知道它的工作解决方案。 stackoverflow.com/help/someone-answers
    • 如果您接受解决方案,就会出现一个绿色勾号,这肯定会帮助其他人
    • 谢谢,我已将其标记为答案,但由于我的声誉不够好,不幸的是,我的支持被公开忽略了 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 2013-12-13
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多