Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Use Google Apps Script to loop through the whole column

I am trying to loop through the whole row in my google sheet and copy some of the data from one sheet to another. The list will get longer over time.

More specifically: If input in column B equals "blue", than copy the values from column A and C into another sheet. Do this for all columns till the end of the column.

Link to my spreadsheet: https://docs.google.com/spreadsheets/d/1xnLygpuJnpDfnF6LdR41gN74gWy8mxhVnQJ7i3hv1NA/edit?usp=sharing

  • The loop stops when the colour does not equal blue. Why?
  • As you can see I used a for loop. Is that even the way to go?
  • Can I do anything about the speed of the code execution?

Any comments, hints or help are highly appreciated.

Regards!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You had the input sheet named "List" and I named the output sheet "Output". And here's the code.

function condCopy()
{
  var s = SpreadsheetApp.getActiveSpreadsheet();
  var sht = s.getSheetByName('List')
  var drng = sht.getDataRange();
  var rng = sht.getRange(2,1, drng.getLastRow()-1,drng.getLastColumn());
  var rngA = rng.getValues();//Array of input values
  var rngB = [];//Array where values that past the condition will go
  var b = 0;//Output iterator
  for(var i = 0; i < rngA.length; i++)
  {
    if(rngA[i][1] == 'blue')
    {
      rngB[b]=[];//Initial new array
      rngB[b].push(rngA[i][0],rngA[i][2]);
      b++;
    }
  }
  var shtout = s.getSheetByName('Output');
  var outrng = shtout.getRange(2,1,rngB.length,2);//Make the output range the same size as the output array
  outrng.setValues(rngB);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...