我如何让makeCopy()在之后运行?

时间:2018-08-04 08:50:40

标签: google-apps-script

我想将电子表格文件复制为新的文件名生效日期,

,但makeCopy方法始终首先运行。

如何让它最后运行还是在一行之后运行?

我尝试过:

1.makemakeCopy方法移至另一个函数并调用它

2。在makeCopy方法之前添加“ while循环”

3。使用“如果”判断电子表格更新时间,然后执行makeCopy方法

4。在makeCopy方法之前使用sleep(60000)

这是我的代码:

function DoCopyfile(){
    Copyfile(0);
    Copyfile(1);
}

function Copyfile(afterweek){

    var thissheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];

    var weekstr = new Array("週一","週二","週三","週四","週五","週六","週日");

    for (var i=0;i<7;i++) {
    thissheet.getRange(1,2+i).setValue(Utilities.formatDate(new Date(new Date().setDate(new Date().getDate()-new Date().getDay()+1+7*afterweek+i)),"GMT+8","MM/dd") + " (" + weekstr[i] + ")");
    }

    var PreMonday = new Date(new Date().setDate(new Date().getDate()-new Date().getDay()+1+7*afterweek));
    var Monday = new Date(Utilities.formatDate(PreMonday,"GMT+8","yyyy/MM/dd 00:00:00"));
    var PreSunday = new Date(new Date().setDate(new Date().getDate()-new Date().getDay()+7+7*afterweek));
    var Sunday = new Date(Utilities.formatDate(PreSunday,"GMT+8","yyyy/MM/dd 23:59:59"));

    var allrange = thissheet.getRange("B2:H25");
    allrange.clear();
    allrange.breakApart();

    var cal = CalendarApp.getCalendarById("My Gmail");
    var events = cal.getEvents(Monday, Sunday, {search: ''});

    for (i=0;i<events.length;i++) {    
        var weekday = events[i].getStartTime().getDay();
        var StartRange = (events[i].getStartTime().getHours()-7)*2+events[i].getStartTime().getMinutes()/30;
        var EndRange = (events[i].getEndTime().getHours()-7)*2+events[i].getEndTime().getMinutes()/30;
        var currentrange = thissheet.getRange(StartRange,1+weekday,EndRange-StartRange,1);
        var when = Utilities.formatDate(events[i].getStartTime(),"GMT+8","hh:mm a")+"-"+Utilities.formatDate(events[i].getEndTime(),"GMT+8","hh:mm a");
        currentrange.merge();
        currentrange.setBorder(true, true, true, true, false, false);
        currentrange.setValue(events[i].getTitle()+"\n"+when);
    }

    var thisfolder = DriveApp.getFolderById("My google drive folder ID");
    var newfilename = "行事曆_" + Utilities.formatDate(Monday,"GMT+8","yyyy-MM-dd") + "_" + Utilities.formatDate(Sunday,"GMT+8","yyyy-MM-dd");
    var destfile = thisfolder.getFilesByName(newfilename);

    while (destfile.hasNext()){
        var file = destfile.next();
        file.setTrashed(true);   
    }

    var newfile = DriveApp.getFileById("My Spreadsheet file ID").makeCopy(newfilename,thisfolder);    

}

1 个答案:

答案 0 :(得分:1)

对不起

一个朋友告诉我使用Promise,

我找到了SpreadsheetApp的方法flush()。

我在makeCopy之前添加了SpreadsheetApp.flush(),它可以正常工作。