问题
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