Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

Get Google Sheets script to repeat the same steps automatically

I am brand new to scripting.

I have a set of numbers in column X that I would like to (one at a time) have copied into cell T1, which will then return a result on Q11. I then want it to copy the result in Q11 and paste it on column Y next to the number originally copied from X

I have managed to start the below 2 different options, how do I get it to keep repeating the steps for every row of column X and Y?

Option 1:

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('T1').activate();
  spreadsheet.getCurrentCell().setFormula('=X1');
  spreadsheet.getRange('Y1').activate();
  spreadsheet.getRange('Q11').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};

Option 2:

function myFunction2() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('T1').activate();
  spreadsheet.getRange('X1').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.getRange('Y1').activate();
  spreadsheet.getRange('Q11').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If Q11 is a simple function that only uses T1 as its input, it would be better to stick to formulas. You can probably use ARRAYFORMULA (see docs) in the first cell to apply it to the entire column (so it’s automatically applied to the entire column).

If that cannot be done or what you want is to practice using Google Apps Script, you can use a simple loop together with getValue and setValue to achieve it:

function computeData() {
 const sheet = SpreadsheetApp.getActiveSheet()
 const inputRange = sheet.getRange('T1')
 const resultRange = sheet.getRange('Q11')
 
 for (let i = 1; i <= sheet.getLastRow(); i++) {
   const xRange = sheet.getRange(`X${i}`)
   const yRange = sheet.getRange(`Y${i}`)
 
   const x = xRange.getValue()
   inputRange.setValue(x)
 
   const result = resultRange.getValue()
   yRange.setValue(result)
 }
}

It’s worth noting that this script is slow and if you can make the algorithm in the script, it’s better to use getValues of all the values in the column, compute them all and finally do setValues to the other column.

Note: The example script requires the V8 runtime (currently the default one). If the Apps Script project is old, make sure that it’s properly set up.

References


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...