首页 > 解决方案 > 如何匹配给定单元格索引上方的字符串

问题描述

我有一个这样的时间表,并以某种方式确定了爱丽丝的位置B7

给定索引B7,我怎样才能找到匹配的日期?这里是 Alice 上方的第一个以 开头的单元格October

标签: google-sheetsgoogle-sheets-formula

解决方案


建议

鉴于每个日期的名称总数是随机的(根据您的样本表,某些日期只有 2 个名称,而其他日期只有 3 个),因此仅使用预定义的函数来实现这一点看起来会非常棘手。

您可以尝试为此方法使用自定义公式,只需将下面的示例函数作为绑定脚本复制并粘贴到您的工作表文件中,然后调整您的设置:

function FINDDATE(cell) {
  var sheet;
  if(cell.split("!").length==1){
    sheet = SpreadsheetApp.getActive().getActiveSheet();
  }else{
    sheet = SpreadsheetApp.getActive().getSheetByName(cell.split("!")[0]);
  }
  var selectedLoc = sheet.getRange(cell);
  for(i=selectedLoc.getRow();  i != 1; i--){
    var dateFound = isValidDate(sheet.getRange(i,selectedLoc.getColumn()).getValue());
    if(dateFound == true){ //Return the date of the very first detected as date above the index
      var res = Utilities.formatDate(sheet.getRange(i,selectedLoc.getColumn()).getValue(), Session.getScriptTimeZone(), "MMMM d");
      return res.toString();
    }
  }
}

function isValidDate(d) { //Check if a cell is a date, reference from https://stackoverflow.com/a/17110249
  if ( Object.prototype.toString.call(d) !== "[object Date]" )
    return false;
  return !isNaN(d.getTime());
}

示例演示:

下面两种方法介绍如何使用FINDDATE自定义函数:

方法一:

在此处输入图像描述

方法二:

在此处输入图像描述

方法 3:在不同的工作表上使用 FINDDATE

在此处输入图像描述


推荐阅读