首页 > 解决方案 > 有没有办法检查单元格中的单词?

问题描述

我正在寻找一种方法来检查单元格是否包含 Google Apps 脚本和 Google 表格中的文本。

var cell = "Joe, Bob, Tim, John"

//I would want this to execute
if(cell contains "Tim") {
//code
}

标签: javascriptif-statementgoogle-apps-scriptgoogle-sheets

解决方案


最近,服务中TextFinder添加了一个类SpreadsheetApp,允许您在现场RangeSheet甚至是Spreadsheet自己)上执行此操作。有关更多详细信息,请参阅文档。只需将查找器设置在上下文中createTextFinder(),并将您要查找的文本作为参数。findNext()在结果TextFinder实例上调用方法将返回Range它被调用的方法,或者null如果没有找到。例如:

function findText() {

  var sh = getSheet(); //custom function that returns target Sheet;
  var rng = sh.getRange(1,1); //change to desired Range boundaries;

  //create TextFinder and configure;
  var tf = rng.createTextFinder('textToFind');
      tf.matchCase(false); //{Boolean} -> match target text's case or not;
      tf.matchEntireCell(false); //{Boolean} -> check the whole Range or within;
      tf.ignoreDiacritics(true); //{Boolean} -> ignore diacretic signs during match;
      tf.matchFormulaText(false); //{Boolean} -> search in formulas (if any) or values;

  //invoke search;
  var res = tf.findNext();

  //do something with result;
  if(res!==null) {
    var vals = res.getValues();
    Logger.log(vals);
  }

}

推荐阅读