Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search spreadsheet by column, return rows

I'm trying to find the best script in terms of runtime to complete a task. I've got a decently large spreadsheet where I need to check values in certain known columns, and depending on a match case it returns that row. Ideally I'd like a new spreadsheet containing the returned rows.

I've got the spreadsheet opened by ID and I've got the sheet & range, but not sure the most efficient way to search through the specific columns and grabbing not just that value but the entire row.

like image 339
Henry David Avatar asked Aug 28 '13 07:08

Henry David


People also ask

How do I use Xlookup in Google Sheets?

XLOOKUP with FILTER function The FILTER function is one of the easiest ways to replicate XLOOKUP in Google Sheets. Here's the basic FILTER function syntax. Specify the range containing the value you want to search or return (C3:C11). Then add the criteria range (A3:A11) and criteria (F3) to your formula.

How do I use Arrayformula in Google Sheets?

Pressing Ctrl+Shift+Enter while editing a formula will automatically add ARRAYFORMULA( to the beginning of the formula. Note that array formulas cannot be exported.


2 Answers

You can use the code below to search in a specific column. Code is self explanatory.

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [ {name: "Search", functionName: "onSearch"} ];
  ss.addMenu("Commands", menuEntries);    
}

function onSearch()
{
    var searchString = "Test11";
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetName"); 
    var column =4; //column Index   
    var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); //1st is header row
    var searchResult = columnValues.findIndex(searchString); //Row Index - 2

    if(searchResult != -1)
    {
        //searchResult + 2 is row index.
        SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 2, 1))
    }
}

Array.prototype.findIndex = function(search){
  if(search == "") return false;
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return i;

  return -1;
} 
like image 120
Aseem Gautam Avatar answered Oct 25 '22 12:10

Aseem Gautam


You may want to use the Google Apps Script textFinder class.

This example function will search a string and show the row of the first occurrence in an alert dialog:

function searchString(){
  var sheet = SpreadsheetApp.getActiveSheet()
  var search_string = "dog"
  var textFinder = sheet.createTextFinder(search_string)
  var search_row = textFinder.findNext().getRow()
  var ui = SpreadsheetApp.getUi();
  ui.alert("search row: " + search_row)
}
like image 36
Jéter Silveira Avatar answered Oct 25 '22 14:10

Jéter Silveira