Find value in spreadsheet using google script

后端 未结 1 1659
南旧
南旧 2021-01-07 09:40

Situation:

  1. 1 spreadsheet
  2. multiple sheets
  3. 1 cell selected (may vary)

What I\'d like to do is to find and set focus to the next

相关标签:
1条回答
  • 2021-01-07 10:14

    Here is an example of such a function, I inserted a drawing in my spreadsheet representing a button which I assigned the script so it's easy to call.

    I added a feature to set a light yellow background on the resulting selected cell so it's easier to see the selected cell but this is optional.

    Code

    function findAndSelect(){
      var sh = SpreadsheetApp.getActiveSpreadsheet();
      var ss = sh.getActiveSheet();
      var cell = ss.getActiveCell();
      cell.setBackground('#ffff55');// replace by cell.setBackground(null); to reset the color when "leaving" the cell
      var activeR = cell.getRow()-1;
      var activeC = cell.getColumn()-1;
      var value = cell.getValue();
      var data = ss.getDataRange().getValues();
      var step = 0
      for(var r=activeR;r<data.length;++r){
        for(var c=activeC;c<data[0].length;++c){
          step++
          Logger.log(step+' -- '+value+'  =  '+data[r][c]);
          if(data[r][c]==''||step==1){ continue };
          if(value.toString().toLowerCase()==data[r][c].toString().toLowerCase()){
            ss.getRange(r+1,c+1).activate().setBackground('#ffff55');
            return;
          }
        }
      }
    }
    

    Caveat

    This code only searches 'downwards', i.e. any occurrence in a row that would precede the selected cell is ignored, same for columns...

    If that's an issue for you then the code should be modified to start iterating from 0. But in this case if one need to ignore the initial starting cell then you should also memorize its coordinates and skip this value in iteration.

    0 讨论(0)
提交回复
热议问题