我有以下Google函数:
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());
};
它在当前行之上创建一个空白行,并将当前行复制到空白行中。这个很管用。
光标(可视)以新行结束。换句话说,在视觉上,当我执行insertRowBefore时,光标保持在原来的位置,下面的行向下移动。
然而,当我在没有事先移动游标的情况下键入单元格(第一列)时,它就会键入游标所在的单元格,只要我按返回键,数据就会“跳转”到下面的单元格,就像我在那里键入一样。这就好像光标实际上在下面的行中,并且UI不同步。然而,警报“告诉我”我是在正确的一行(一个是空的,然后填满)。
有趣的是,如果我在不移动UI中的游标的情况下重新运行函数,我注意到活动行增加了一个。因此,我认为UI在函数完成后移动游标,但未能以图形方式显示它。
我的问题是:我怎样才能:
发布于 2022-05-16 23:07:15
我通过将以下3行添加到函数的末尾来修正它:
destinationSheet.getRange(currentRow - 1, 1, 1, destinationSheet.getLastColumn()).activate();
destinationSheet.getRange(currentRow, 1, 1, destinationSheet.getLastColumn()).activate();
destinationSheet.getRange(currentRow, 1).activate();
只有这样我才能让它发挥作用。它:
然后,当我键入单元格时,当我点击enter时,它不会掉下一行。请注意,对于额外代码的前2行,需要选择比第一列更多的内容--因此需要选择整个行。因此,问题在前2行代码之后得到了解决。第三种只是修饰,只选择行中的第一列。
我不知道为什么这样做,为什么其他变体不起作用。
发布于 2022-05-15 15:22:03
Google脚本电子表格服务没有控制光标位置的方法,但是它能够设置活动单元格。在许多国家中,有一个办法是:
function setCurrentCell(){
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadsheet.getSheetByName('Sheet1');
const range = sheet.getRange('B2'); // This should be a single cell
range.activateAsCurrentCell();
}
另一种方法是对Range对象使用activate()
。当前单元格将是范围内的左上角单元格。
参考文献
相关
https://stackoverflow.com/questions/72247443
复制相似问题