如何使Google Sheets函数引用从中调用它的单元格 [英] How to make a google sheets function reference the cell it was called from

查看:0
本文介绍了如何使Google Sheets函数引用从中调用它的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我遵循了this tutorial,它基本上使按钮调用Google Sheet脚本,如下所示

function jumpToDetail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("details");
  ss.setActiveSheet(sheet).setActiveSelection("A2");
}

这会使您跳到特定的单元格。我查看了Google Sheetsdocs,但不知道如何使此函数引用从中调用它的单元格

问题

如何使Google Sheets中的函数引用从中调用该函数的函数。例如,我希望最终代码如下所示:

function jumpToDetail(clickedCell) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("details");
  // get the value of "id" of the same row the cell was clicked in
  ss.setActiveSheet(sheet).setActiveSelection(function_of(id));
}

推荐答案

活动范围通过SpreadsheetAppgetActiveRange方法获取。当从定制函数调用脚本时,这很有用:活动范围就是定制函数所在的单元格。示例:

function currentCell() {
  return SpreadsheetApp.getActiveRange().getA1Notation();
}
在工作表中的任何位置输入=currentcell()将返回该单元格的A1表示法。

但是,单击按钮(插入的图形)对活动范围没有影响,因为图形不与工作表中的任何单元格关联。它们在自己的层中,漂浮在床单上。在使用按钮调用的脚本中,活动区域位于选定单元格所在的任何位置,与按钮的位置无关。

为了将某个位置传递给脚本,用户必须首先选择一个单元格,然后(通过按钮或菜单)调用脚本。

下面是一个函数,它返回当前行中带有"id"列的单元格的内容。(假定标签位于工作表的第一行。)

function getId() {
  var row = SpreadsheetApp.getActiveRange().getRow();
  var sheet = SpreadsheetApp.getActiveSheet();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var column = headers[0].indexOf('id') + 1;
  if (column > 0) {
    return sheet.getRange(row, column).getValue();
  }
  else {
    throw new Error('No column labeled id');
  }
}

这篇关于如何使Google Sheets函数引用从中调用它的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆