问题
I am transitioning from Excel and VBA to Google Sheets and admittedly, don't know JavaScript.
I see that there is a common request for some VBA which will copy down the formulas from the row above, when I insert a new row anywhere in the dataset. I know how to add a butt, and i used the Macro Recorder to record the insertion of a Row, but the recorder only records that particular row that I chose to insert above.
I'd like the script to grab the activecell row number, so that it is dynamic on where ever my cursor is.
Here's the code I have so far. Can someone help me correct it?
function test() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getActiveCell().getRow().activate();
spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveCell().getRow(), 1);
spreadsheet.getActiveCell().offset(0, 0, 1, spreadsheet.getActiveCell().getNumColumns()).activate();
};
回答1:
Solution:
You can accomplish your goal by creating an installable onChange trigger.
Follow the instructions below to set it up. After the setup is completed, you don't execute myFunction manually. It will be executed automatically everytime you insert a new row in the active sheet.
function myFunction(e) {
const sh = SpreadsheetApp.getActiveSheet();
if(e.changeType === 'INSERT_ROW') {
const row = sh.getActiveRange().getRow();
const formulas = sh.getRange(row-1,1,1,sh.getLastColumn()).getFormulasR1C1();
sh.getRange(row,1,1,sh.getLastColumn()).setFormulasR1C1(formulas);
}
}
Instructions:
Go to use the aforementioned code, copy/paste it to the script editor and click save.
Click on the current project's triggers:
Click on add trigger on the bottom right side of the page.
And then use exactly these settings:
来源:https://stackoverflow.com/questions/64037593/google-sheets-copy-down-formula-with-inserting-a-row