Google table script: filter by value, copy and paste individual columns, not the entire range

96 Views Asked by At

Good health to all! In this case, the row contains 136 columns, we filter by the 8th column, then we need to copy and paste into another file, for example, columns 134-136. I set the range var rng = sht.getRange(3,134,10000,3), I thought it would be similar to the FILTER() function, but no - the script works only if the range contains a column by which we filter... There was also a decision to insert all 136 columns and delete unnecessary 133, but this is generally, as it seems to me, inhumane.

Can you tell me what needs to be changed in the existing code so that you can copy and paste a filtered range that does not contain the column that is being filtered? How can the script be modified so that it can be filtered by two or more columns? Here I found a piece of code that filters the Google table by value and inserts the selected rows into the specified sheet.

I would be grateful for a tip on the optimal solutions for each issue

function CopyPaste()
{//the quantity is written
  const SOURCE1 = SpreadsheetApp.openById("Here is the Google table ID");
  const sht = SOURCE1.getSheetByName("Sales");
  
var ss = SpreadsheetApp.getActive();
var sheet2 = ss.getSheetByName("Monitor"); //settings sheet
var diap = sheet2.getRange("A1").getValue(); //value for the filter

  var rng = sht.getRange(3,1,10000,136);// filtered range
  var PasteSht = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet 3');// sheet for inserting data in the current workbook
  var rngA = rng.getValues();//this is where a fragment of someone else's code came from (I didn't rename variables)
  var yesesA = []
  for(var i=0;i<rngA.length;i++)
  {
    if(rngA[i][7]==diap)
    {
      yesesA.push(rngA[i])
    }
  }
  var yesesRng = PasteSht.getRange(3, 1, yesesA.length, yesesA[0].length);
  yesesRng.setValues(yesesA);
}

1

There are 1 best solutions below

0
TheWizEd On

Try this

Code.gs

function CopyPaste() { //the quantity is written
  const SOURCE1 = SpreadsheetApp.openById("Here is the Google table ID");
  const sht = SOURCE1.getSheetByName("Sales");
  
  var ss = SpreadsheetApp.getActive();
  var sheet2 = ss.getSheetByName("Monitor"); //settings sheet
  var diap = sheet2.getRange("A1").getValue(); //value for the filter

  var rng = sht.getDataRange(); // filtered range
  var PasteSht = ss.getSheetByName('Sheet 3');// sheet for inserting data in the current workbook
  var rngA = rng.getValues();//this is where a fragment of someone else's code came from (I didn't rename variables)

  var yesesA = rngA.filter( row => row[7] === diap ); // filter out all rows including diap

  ysesA = yesesA.map( row => row.slice(132,136) ); // Array.slice(from,to(not including)) columns 133-136

  var yesesRng = PasteSht.getRange(3, 1, yesesA.length, yesesA[0].length);
  yesesRng.setValues(yesesA);
}

Reference