Reputation: 1127
I want to print the timestamp in the last row of column A once I click a button so that I don't need to use the shortcut key CTRL + SHIFT + ;
to generate the timestamp as shown in the screenshot below:
This is my script:
function myFunction() {
const dt = Utilities.formatDate(new Date(), 'Asia/Singapore', 'HH:mm:ss');
var ss = SpreadsheetApp.getActiveSheet ();
var direction = SpreadsheetApp.Direction
var aLast = ss.getRange("A"+(ss.getLastRow()+1)).getNextDataCell(direction.UP).getRow()
var destRange = ss.getRange(aLast+1,1);
destRange.setValue(dt)
}
I assigned the function to the button and run the script, but this is the error that show to me:
I'm still new to google apps script, may I know where did I did wrong in my script? Any advise will be appreciated!
Upvotes: 1
Views: 75
Reputation: 201613
In your situation, I thought that the last row might be the same with the bottom row of the sheet. In this case, such error occurs. In your script, when the values of ss.getLastRow()
and ss.getMaxRows()
are the same, I think that the error occurs. If my understanding is correct, in order to avoid this, how about the following modification?
function myFunction() {
const dt = Utilities.formatDate(new Date(), 'Asia/Singapore', 'HH:mm:ss');
var ss = SpreadsheetApp.getActiveSheet();
var direction = SpreadsheetApp.Direction
// I modified below script.
var lastRow = ss.getLastRow();
var destRange;
if (lastRow == ss.getMaxRows()) {
destRange = ss.getRange("A" + (lastRow + 1));
} else {
var aLast = ss.getRange("A" + (lastRow + 1)).getNextDataCell(direction.UP).getRow();
destRange = ss.getRange(aLast + 1, 1);
}
destRange.setValue(dt);
}
Upvotes: 2