How to check if the value exist in google spreadsheet or not using apps script

前端 未结 2 952
粉色の甜心
粉色の甜心 2021-01-17 05:01

How to check if the value is exist in google spreadsheet or not using apps script I want to check if the Sam exist in the entire spreadsheet or not using apps s

相关标签:
2条回答
  • 2021-01-17 05:52

    Depending on if you want to select the range or just always use the whole A:A column. In the former case, do this:

    // this gets the range
    var range = SpreadsheetApp.getActiveRange().getValues();
    
    // this is what you are searching for
    var searchString = "Sam";
    
    // this is whether what you are searching for exists 
    var isSearchStringInRange = range.some( function(row){
        return row[0] === searchString
    });
    
    // then you can proceed to do something like
    if( isSearchStringInRange ){
      // do something
    }
    
    0 讨论(0)
  • 2021-01-17 05:59

    Answer:

    You can define a textFinder and run it over your data range.

    Code:

    function findSam() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];  
      var range = sheet.getDataRange();
      var textFinder = range.createTextFinder('Sam');
      var locations = [];
      
      var occurrences = textFinder.findAll().map(x => x.getA1Notation());
      
      if (occurrences == []) {
        // do something if "Sam" not in sheet 
      }
      else {
        // do stuff with each range: 
      }  
    }
    

    This code will:

    • Find all cells that contain "Sam" in the first sheet of the Spreadsheet
    • Append the Range object that contains "Sam" to an array of ranges
    • Map the array of ranges to an array of A1 notations which are all the cells which contain "Sam".

    From here you can do what you wish with the ranges. If "Sam" is not in the sheet then occurrences will be an empty array and you can do here what you wish.

    I hope this is helpful to you!

    References:

    • Class TextFinder | Apps Script | Google Developers
    0 讨论(0)
提交回复
热议问题