Find position of a cell containing a specific string

六月ゝ 毕业季﹏ 提交于 2021-02-05 08:54:05

问题


I'm looking for a way to search for a string in a range and get the position of the cell once found.
Here's what I use to find the row number

var ss = SpreadsheetApp.getActiveSheet();
var values = ss.getRange("B:B").getValues();
var i=rownum=0;
for(i=0;i<values.length;i++) {
  if(values[i]=='string') rownum=i+1;  

I then use the following code to find the column number

var colvalue;
for (j=1;j<ss.getLastColumn();j++) {
if (ss.getRange(3,j).getValue() == "string" {
colvlaue = j;
  }
}

Is there a way to search both entire rows and columns within a range that contains a specific string and return its cell position once it finds it?


回答1:


You need to use a nested for loop. This code will do it:

function findValueInRange (po) {
  /*
    po.whatToFind - the string value to find

  */

  var colvalue,i,j,L,L2,ss,theLastColumn,theLastRow,thisRow,values;

  ss = SpreadsheetApp.getActiveSheet();
  theLastColumn = ss.getLastColumn();
  theLastRow = ss.getMaxRows();
  
  //Returns a two dimensional array of both rows and columns
  values = ss.getRange(1,1,theLastRow,theLastColumn).getValues();
       
  
  whatToFind = po.whatToFind;
  
  L = values.length;

  for(i=0;i<L;i++) {
    thisRow = values[i];
    L2 = thisRow.length;

    for (j=0;j<L2;j++) {
      colvalue = thisRow[j];

      if (colvalue === whatToFind) {
        Logger.log("The string is in row: " + (i + 1) + " and column: " + (j+1));
      };
    };
  };
};


来源:https://stackoverflow.com/questions/32282187/find-position-of-a-cell-containing-a-specific-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!