Googlescript加一周

时间:2018-11-07 18:45:19

标签: google-apps-script google-sheets

我有一个脚本,可以向C(oldDateRange)添加一个星期,并将结果放入D(NextWeek),但效果不佳。

我还需要向D添加一个星期,并将结果放入E。如果我更改C,则D和E列将增加一周。如果我更改D,则E增加一周。

function addWeek() {

var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");

var oldDate  = sheet.getRange("oldDateRange").getValue();

var oldDateValue = oldDate.getMilliseconds()

var nextWeekValue = oldDateValue + 1000*60*60*24*7
var nextWeekDate = new Date(nextWeekValue)

var cell = sheet.getRange("NextWeek"); 
cell.setValue(nextWeekDate);

}  

1 个答案:

答案 0 :(得分:0)

答案是将7添加到旧的Date属性,并使用它设置新的Date。答案可以在这里找到。 Add days to JavaScript Date

function addWeek() 
{

  var ss = SpreadsheetApp.getActive();
  // I just added the id for accuracy

  var sheet = ss.getSheetByName("Sheet1");

  var lrow = sheet.getLastRow();
  // get the last row in the spreadsheet so when know when to stop for our 
  //loop

  var oldDates = sheet.getRange(2, 4, lrow, 1).getDisplayValues();
  //the displayvalue returns whatever is in the cell

  var newDates = sheet.getRange(2, 5, lrow, 1);
  Logger.log(newDates.getDisplayValues().length);
  // I get the range instead of the value because I will set values here.  

  for(var i = 1; i < lrow;i++)
  {
    var date = new Date(oldDates[i][0]); 
    // gets the current date cell and creates a date from it
    var newDate = date;
    // creates a new date
    newDate.setDate(date.getDate() + 7);
    //sets the date adding a week
    newDates.getCell(i, 1).setValue(newDate);
   //sets the cell to the right with the date.
  }
}