I have the following Google Sheets function:
function addRow() {
var destinationSheet = SpreadsheetApp.getActiveSheet();
var currentRow = destinationSheet.getActiveCell().getRow();
// Insert the row
destinationSheet.insertRowBefore(currentRow);
// Copy the source to destination (currentRow is the blank line)
var sourceRange = destinationSheet.getRange(currentRow + 1, 1, 1, destinationSheet.getLastColumn());
var targetRange = destinationSheet.getRange(currentRow - 0, 1, 2, destinationSheet.getLastColumn());
// Fill upwards
sourceRange.autoFill(targetRange, SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
SpreadsheetApp.getUi().alert(destinationSheet.getActiveCell().getRow());
};
It creates a blank row above the current one and copies the current row into the blank one. This works.
The cursor (visually) ends up in the new row. In other words, visually, when I do the insertRowBefore, the cursor stays where it is and the rows below move down.
However, when I then type into the cell (first column) without moving the cursor beforehand, it types into the cell where the cursor is but the moment I press Return, the data "jumps" to the cell below as if I had been typing there. It is as if the cursor is actually in the row below and the UI is out of sync. The alert, however, "tells" me I am in the right row (the one that was empty and then filled).
Interestingly, if I re-run the function without moving the cursor in the UI, I notice that the active row has incremented by one. So, I think that the UI moves the cursor after the function has finished but fails to show it graphically.
My question is: how do I either:
- Get the UI to show the active cursor location correctly? OR, ideally
- Prevent this "behind the scenes" movement of the cursor so that it remains in the correct cell (column 1 of the row that was added).