简体   繁体   English

查找包含特定字符串的单元格的位置

[英]Find position of a cell containing a specific string

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?有没有办法在包含特定字符串的范围内搜索整行和整列,并在找到后返回其单元格位置?

You need to use a nested for loop.您需要使用嵌套for循环。 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));
      };
    };
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM