首页 > 解决方案 > 如何通过单击 Google 表格中的按钮弹出当前星期一?

问题描述

我想用 App Script 在 Google 电子表格中构建一个按钮。请求如下:

  1. 单击名为“刷新”的按钮
  2. 弹出当前一周的星期一的日期,例如今天是 5/7/2021,那么单元格值应该填写 5/3/2021。

我知道可以通过编写脚本来实现,但我不知道如何实现。

谢谢, 杰特

==================================================== =========================

function popMonday() {
var sheet = SpreadsheetApp.getActiveSheet();
var cell = SpreadsheetApp.getActiveSpreadsheet().getSheets()[4].getRange('L1');
SpreadsheetApp.setCurrentCell(cell);

var selection = SpreadsheetApp.getSelection();
var currentCell = selection.getCurrentCell();

const today = new Date();
const tw = today.getDay();
const dateObj = new Date(today.setDate(today.getDate() - (tw - (tw > 0 ? 1 : -6))));
const str = Utilities.formatDate(dateObj, Session.getScriptTimeZone(), "MM/dd/yyyy");

currentCell.setValue(str);}

标签: google-apps-scriptgoogle-sheets

解决方案


我相信你的目标如下。

  • 您想使用 Google Apps 脚本从今天开始检索这个星期一的日期。
  • 您想打开一个包含检索日期的对话框。

在这种情况下,下面的脚本怎么样?

示例脚本:

function myFunction() {
  const today = new Date();
  const tw = today.getDay();
  const dateObj = new Date(today.setDate(today.getDate() - (tw - (tw > 0 ? 1 : -6))));
  const str = Utilities.formatDate(dateObj, Session.getScriptTimeZone(), "MM/dd/yyyy");
  Browser.msgBox(str); // or SpreadsheetApp.getUi().alert(str);
}
  • 在这种情况下,我认为检索星期几getDay()很重要。

  • 运行该函数myFunction时,会打开一个对话框。您可以在对话框中看到日期。

  • then the cell value should be filled with 5/3/2021.,当您使用以下脚本而不是 时Browser.msgBox(str);,当脚本运行时,将打开一个对话框,并将 的值dateObj放入活动单元格。

      SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(str), "sample");
      SpreadsheetApp.getActiveRange().setValue(dateObj);
    

参考:


推荐阅读