Reputation: 125
I have a custom function like this:
var today = new Date();
var date = (today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
return dateTime;
And I call the function above in the cells in Google Sheet. But everytime I open the sheet, all the function re-run and get a new timestamp. Is there a way to prevent this?
Upvotes: 1
Views: 854
Reputation: 15377
You can utilise the Sheet.getCurrentCell()
method to check if the cell already has a value and return it back if it does:
function getTimestamp() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const cell = ss.getActiveSheet().getCurrentCell()
if (cell.getDisplayValue() !== "" && cell.getDisplayValue() !== "Loading...") {
return cell.getDisplayValue()
}
var today = new Date()
var date = (today.getMonth() + 1) + '-' + today.getDate() + '-' + today.getFullYear()
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()
var dateTime = date + ' ' + time
return dateTime
}
As per the documentation on Custom Functions in Google Sheets:
Custom functions can call certain Apps Script services to perform more complex tasks.
and:
Spreadsheet | Read only (can use most
get*()
methods, but notset*()
).
So the idea is thus:
Upvotes: 2