Google脚本:在新的相邻单元格中添加结果

时间:2019-01-22 20:23:26

标签: google-apps-script

在Google电子表格中,我想为F列中的日期添加7天。结果应显示在G列中。如何在相邻的单元格G列中打印函数的结果? 抱歉,如果我的问题听起来很简单,我是一个新手。这是我的代码:

function UpdateDates() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var row = SpreadsheetApp.getActiveRange().getRow
    //Get the dates from the cell and convert them into Milliseconds since 1970/01/01
    var First = new Date(ss.getRange('F4').getValue()).getTime();
    var Second = new Date(ss.getRange('F5').getValue()).getTime()
    var Third = new Date(ss.getRange('F6').getValue()).getTime();
    var dayInMs = 24*60*60*1000    //one day in Milliseconds
    //add sevendays to each date in milliseconds

    First = First + (7*dayInMs)
    Second += (7*dayInMs)
    Third += (7*dayInMs)

   //Convert Milliseconds to date use new Date(time in ms) and set Values of the cell
    ss.getRange('F4').setValue(new Date(First));
    ss.getRange('F5').setValue(new Date(Second));
    ss.getRange('F6').setValue(new Date(Third));

}

现在,当我运行代码时,它将替换F列中的内容

1 个答案:

答案 0 :(得分:0)

尝试一下:

function UpdateDates() {
    var ss=SpreadsheetApp.getActive();
    var sh=ss.getActiveSheet();
    var rg=sh.getRange(4,6,3,2);
    var vA=rg.getValues();
    var day=1000 * 60 * 60 * 24;
    for(var i=0;i<vA.length;i++){
      vA[i][1]=new Date(vA[i][0].getFullYear(),vA[i][0].getMonth(),vA[i][0].getDate()+ 7);
      //vA[i][1]=new Date(new Date(vA[i][0]).valueOf()+ (7 * day));
    }
    sh.insertColumnAfter(6);
    rg.setValues(vA);
}