我如何自动将 google 工作表中的按钮脚本编写为 'Jump to current date'

How do i script button in google sheets to 'Jump to current date' automatically

我有很多 sheets 的数字 - 我想在 google sheets 中创建一个按钮,它允许我跳转到今天的日期(日期是在专栏中)

我知道如何创建超级 link 但是我想单击按钮而不是文本 - google sheets 只允许您将脚本添加到按钮而不是超级links.

有谁知道如何在 google sheet 中编写一个按钮以自动跳转到 sheet 上的当前日期?

转到今天的日期

function gotoCurrentDate() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet Name');
  const sr = 2;//data start row
  const hA = sh.getRange(1, 1, 1, sh.getLastColumn()).getValues().flat();//might need to edit header row
  const vs = sh.getRange(sr, 1, sh.getLastRow() - sr + 1, sh.getLastColumn()).getValues();
  const dt = new Date();
  const dts = Utilities.formatDate(dt,Session.getScriptTimeZone(),"MMM dd, yyyy");//might want to change format
  const pos = { col: {}, idx: {} };
  hA.forEach((h, i) => { pos.col[h] = i + 1; pos.idx[h] = i; });
  vs.forEach((r,i) => {
    let d = new Date(r[pos.idx['Date Column Header Name']]);
    let ds = Utilities.formatDate(d,Session.getScriptTimeZone(),"MMM dd, yyyy");//might wat to change format
    if(ds == dts) {
      sh.getRange(i + sr, pos.col['Data Column Header Name']  ).activate()
    }
  });
}

您可以转到 Google Apps Script Reference 并使用搜索框查找您不了解的任何功能。

如果它是一个纯 JavaScript 函数,go here

<input type="button" value="Go To Current Date" onClick="google.script.run.gotoCurrentDate();" />

将其放入侧边栏的 html 并使用以下函数启动侧边栏。当您打开一个 html 文件时,它会附带一些 html 将其放入正文并保存。

如果您有多个输入控件,您可能希望将其放在头部。

<style> input {margin: 1px 2px 1px 0}; 

gs:

function launchSideBar() {
  SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('sidebar html file name. Do not include the extension').setTitle('Sidebar Title'))
}

今天我在回答问题时使用的电子表格中的边栏如下所示:

您可以直接在电子表格上使用按钮,但我个人认为它们是 PITA。

以防万一,这是精简版(带有自定义菜单而不是按钮):

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('️ Scripts')
    .addItem('Jump to current date', 'jump_to_current_date')
    .addToUi()
}

function jump_to_current_date() {
  var ss    = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName('Sheet1');
  var dates = sheet.getRange('A1:A').getDisplayValues().flat();
  var date  = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy/MM/dd");
  var row   = dates.indexOf(date) + 1;

  if (row > 0) { sheet.getRange('A' + row).activate() }
  else { ss.toast('No current date was found') }
}

代码在 sheet 'Sheet1' 的 'A' 列中搜索日期,并假设日期格式为“2021/11/30”。对于 运行 它创建的脚本 'Custom menu':

当然你可以draw a 'button'触发函数jump_to_current_date(),如果它适合你。