如何检查数值是否在谷歌工作表的单元格范围内



我想使用谷歌工作表的应用程序脚本来查找某个值是否在范围内。

var sheet = SpreadsheetApp.getActiveSheet();
var rangeBikeNumbers = sheet.getDataRange("A5:A5000");
var values = rangeBikeNumbers.getValues();

如果我有我的范围rangeBikeNumbers;42〃;例如在该范围内。我找了好几个小时都找不到答案。indexOf似乎只返回-1,无论该值是否在该范围内。

例如,var indexDataNumber = values.indexOf(42);最终总是-1

我相信你的目标如下。

  • 您想要检查42的值是否存在于A5:A5000的范围内

在这种情况下,我建议使用TextFinder。因为当使用Texfinder时,工艺成本较低。顺便说一下,getDataRange没有参数。从你的剧本来看,我认为你可能想要var rangeBikeNumbers = sheet.getRange("A5:A5000");

当这反映到您的脚本中时,它将变为如下。

修改的脚本:

function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var rangeBikeNumbers = sheet.getRange("A5:A5000");
var find = rangeBikeNumbers.createTextFinder("42").matchEntireCell(true).findNext();
if (find) {
// In this case, the value of 42 is existing in the range.
} else {
// In this case, the value of 42 is NOT existing in the range.
}
}

注:

关于var indexDataNumber = values.indexOf(42); for example always ends up being -1,我认为这个问题的原因是因为values是二维数组。如果要使用此脚本,还可以使用以下脚本。
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var rangeBikeNumbers = sheet.getRange("A5:A5000");
var values = rangeBikeNumbers.getValues();
var find = values.map(([e]) => e).indexOf(42); // of values.flat().indexOf(42);
if (find > -1) {
// In this case, the value of 42 is existing in the range.
} else {
// In this case, the value of 42 is NOT existing in the range.
}
}

参考文献:

  • 基准:使用Google Apps脚本在电子表格中搜索值的过程成本
  • getDataRange((
  • getRange(a1Notation(
  • createTextFinder(findText(

选择要搜索的任何活动范围,它将在该范围内搜索种子。种子当前默认为42,但您可以更改它。

function findSeedInRange(seed = 42) {
const ui = SpreadsheetApp.getUi();
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const rg = sh.getActiveRange();
const row = rg.getRow();
const col = rg.getColumn();
var found = false;
rg.getValues().forEach((r, i) => {
r.forEach((c, j) => {
if (c == seed) {
let r = sh.getRange(i + row, j + col).getA1Notation();
ui.alert(`Found ${seed} in ${r}`);
found = true;
}
})
})
if(!found) {
ui.alert(`Did not find ${seed}`);
} else {
ui.alert('That is all.')
}
}

这是另一种方法:

function findSeedInRange() {
const ui = SpreadsheetApp.getUi();
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const rg = sh.getActiveRange();
const resp = ui.prompt('Enter Seed', 'Enter Seed', ui.ButtonSet.OK_CANCEL)
if (resp.getSelectedButton() == ui.Button.OK) {
var seed = parseInt(resp.getResponseText());
const row = rg.getRow();
const col = rg.getColumn();
var found = false;
rg.getValues().forEach((r, i) => {
r.forEach((c, j) => {
if (c == seed) {
let r = sh.getRange(i + row, j + col).getA1Notation();
ui.alert(`Found ${seed} in ${r}`);
found = true;
}
});
});
if (!found) {
ui.alert(`Did not find ${seed}`);
} else {
ui.alert('That is all.')
}
} else {
ui.alert('Operation cancelled.')
}
}

相关内容

最新更新