Kyle
Kyle

Reputation: 49

Google App Script - copy and increment Date to next row

I have a column with date

var range = sheet.getRange(1,1);
range.copyTo(sheet.getRange(2,1));

give me the same date as previous row.

The above code works well for values and formulas, but not date.

How do I copy it such that it replicate the dragging behaviour, i.e. 11/6/2021 become 12/6/2021.

I have already formatted it as date, I can increment it by manually dragging the cell in UI, but I can't use copyTo in app script to achieve the same result.

Upvotes: 0

Views: 787

Answers (1)

Kin Siang
Kin Siang

Reputation: 2699

In Apps Script, you need to convert to cell values to Date format in order to increment the date as google sheet is using Java Script by adding customize function, below is the way you can add Day + 1 in the next row using Javascript new Date() method:

function increRow(){
  var ss = SpreadsheetApp.getActiveSheet();
  var date = new Date( ss.getRange(1,1).getValue());
  ss.getRange(2,1).setValue(new Date(date.setDate(date.getDate() + 1)));
}

enter image description here

You may try another method autofill which perform as human action to fill Range("A2:A4"), if you preferred:

function autoFill() {
  var spreadsheet = SpreadsheetApp.getActiveSheet();
  
  spreadsheet.getRange(2,1).autoFill(spreadsheet.getRange(2,1,3,1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
 
};

Upvotes: 1

Related Questions