Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

google sheets - .setValue is only executed when the script is finished

D I have a problem with my Script. a part of my script:

    var a = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("A");
    var b = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("B");

    a.getRange("A14").setValue("external File");
    Utilities.sleep(2000);
    a.getRange("A14:C29").copyTo(b.getRange("A1:C15"), {contentsOnly:true});
    a.getRange("A14:C29").clearContent();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To elaborate on @Jack Brown's comment, when both writing to and reading from the Spreadsheet interface, Google Apps Script does not necessarily immediately perform the write - it will attempt to optimize calls over the Spreadsheet interface to minimize resources needed. Using SpreadsheetApp.flush() instructs the Apps Script engine to perform any pending changes to the spreadsheet (writes, calculations of cell formulas due to newly-written data, etc).

OP's snippet would then be:

var a = SpreadsheetApp.getActive().getSheetByName("A");
var b = SpreadsheetApp.getActive().getSheetByName("B");

a.getRange("A14").setValue("external File");

// Force the above value to be written (and any cells that refer to A14 to update).
SpreadsheetApp.flush();

// Without flush(), Apps Script may wait until making these calls to perform the write.
a.getRange("A14:C29").copyTo(b.getRange("A1:C16"), {contentsOnly: true});
a.getRange("A14:C29").clearContent();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...