javascriptgoogle-sheetsgoogle-apps-script

How to Select Specific Ranges in Results


Is it possible to retrieve data based on your preferences? For example, I only need to display columns 1, 5, 8, 11, and 23.

function showInputBox(){

 var ui = SpreadsheetApp.getUi();
 var input = ui.prompt("Please enter your rep name.",ui.ButtonSet.OK_CANCEL);

if(input.getSelectedButton() == ui.Button.OK){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ws = ss.getSheetByName("Monitoring (Database)");
  var data = ws.getRange("A2:X" + ws.getLastRow()).getValues();
  var userSelectedRep = input.getResponseText();
  var newData = data.filter(function(r){ return r[23] == userSelectedRep});
  var newWs = ss.insertSheet(userSelectedRep);
  newWs.getRange(2, 1, newData.length, newData[0].length).setValues(newData);


}

I tried to use getRangeList, but it’s not working. I’m not sure if it’s possible. I’m just a newbie trying to add a script to my Google Sheets data.


Solution

  • You don't need getRangeList. You can filter the columns manually by extracting the required only the columns you want (1, 5, 8, 11, and 23).

    function showInputBox() {
      var ui = SpreadsheetApp.getUi();
      var input = ui.prompt("Please enter your rep name.", ui.ButtonSet.OK_CANCEL);
    
      if (input.getSelectedButton() == ui.Button.OK) {
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var ws = ss.getSheetByName("Monitoring (Database)");
        var data = ws.getRange("A2:X" + ws.getLastRow()).getValues();
        var userSelectedRep = input.getResponseText();
    
        // Filter the data by the rep name in column 24 (23 in zero-index)
        var newData = data.filter(function (r) { return r[23] == userSelectedRep });
    
        // Extract only columns 1, 5, 8, 11, and 23
        var selectedColumns = newData.map(function (r) {
          return [r[0], r[4], r[7], r[10], r[22]];
        });
    
        // Create a new sheet and set the selected data accordingly
        var newWs = ss.insertSheet(userSelectedRep);
        newWs.getRange(2, 1, selectedColumns.length, selectedColumns[0].length).setValues(selectedColumns);
      }
    }