google-apps-scriptgoogle-sheets

How can I check if a numerical value is within a range of cells in google sheets?


I would like to find if a certain value is in a range using app scripts for google sheets.

var sheet = SpreadsheetApp.getActiveSheet();
var rangeBikeNumbers = sheet.getDataRange("A5:A5000");
var values = rangeBikeNumbers.getValues();

If I have my range rangeBikeNumbers, how can I check if the number "42" for example is in that range. I have searched for hours now and have beeb unable to find any answer to this. indexOf only seems to return -1, regardless of whether or not the value is in the range.

var indexDataNumber = values.indexOf(42); for example always ends up being -1


Solution

  • I believe your goal as follows.

    In this case, I would like to propose to use TextFinder. Because when TexiFinder is used, the process cost is low. Ref By the way, getDataRange has not arguments. From your script, I thought that you might want var rangeBikeNumbers = sheet.getRange("A5:A5000");.

    When this is reflected to your script, it becomes as follows.

    Modified script:

    function myFunction() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var rangeBikeNumbers = sheet.getRange("A5:A5000");
      var find = rangeBikeNumbers.createTextFinder("42").matchEntireCell(true).findNext();
      if (find) {
    
        // In this case, the value of 42 is existing in the range.
    
      } else {
    
        // In this case, the value of 42 is NOT existing in the range.
    
      }
    }
    

    Note:

    References: