How do I search Google Spreadsheets?

MXMLLN picture MXMLLN · May 30, 2012 · Viewed 28k times · Source

I am doing a few exhaustive searches and need to determine if a new domain (URL) is already in a Spreadsheet. However, none of the Spreadsheet objects have search functions, namely findText() found in most Document objects. I feel like I am missing something significant. What am I missing?

findText function: https://developers.google.com/apps-script/class_table#findText

SearchResult object: https://developers.google.com/apps-script/class_searchresult

Spreadsheet object: https://developers.google.com/apps-script/class_sheet

My best guess is to try and convert specific Spreadsheet ranges in Document tables, then perform the search. Mendokusai

Answer

Eric Koleda picture Eric Koleda · May 30, 2012

Unfortunately there is no searching functionality in the Spreadsheet services. You can get the data for the range you are searching on, and then iterate over it looking for a match. Here's a simple function that does that:

/**
 * Finds a value within a given range. 
 * @param value The value to find.
 * @param range The range to search in.
 * @return A range pointing to the first cell containing the value, 
 *     or null if not found.
 */
function find(value, range) {
  var data = range.getValues();
  for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].length; j++) {
      if (data[i][j] == value) {
        return range.getCell(i + 1, j + 1);
      }
    }
  }
  return null;
}