【问题标题】:Google Sheets: Show values on a tab depending on dateGoogle表格:根据日期在选项卡上显示值
【发布时间】:2021-06-21 08:20:16
【问题描述】:

我们有一家餐厅,想在带有谷歌表格的屏幕上显示菜单。 我在 Google 表格中使用了 2 个选项卡,主选项卡(编号 1)向访问者显示菜单,第二个选项卡(编号 2)包含从今天到未来 6 周的所有日期,例如:

Column A Column B Column C Column D
21 June Appetizer this day Main dish this day Desert today
22 June Appetizer this day Main dish this day Desert today
23 June Appetizer this day Main dish this day Desert today

等等。等等

现在我们想要的是在今天这一天将 3 个菜单项复制到主选项卡,所以如果是 6 月 22 日,则将相应的开胃菜、主菜和甜点复制到主选项卡。

这可能吗?

【问题讨论】:

  • 你能分享一下你到目前为止的尝试吗?
  • @SefRutten 是的,使用 Apps 脚本可以很容易地完成。我需要更多信息,例如在第一张表中,您希望添加哪些单元格的值?第二张表中的日期是用DATE() 函数创建的吗?

标签: date google-apps-script google-sheets triggers


【解决方案1】:

这可以通过 Google Apps 脚本来实现。您可以使用 JavaScript 代码 sn-p 为您执行此操作。


打开所需的电子表格。转到 Tools 菜单并单击 Script Editor。这将打开一个空函数的脚本编辑器窗口,代码必须写在这个函数中,给它一个名字,我用的是updateFood()

function updateFood() {
      // Fetch all the sheets/tabs of the current spreadhsheet
      let sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

      // Select the second sheet/tab using [1], first tab will be [0]
      // Fetching the second sheet because that is where the data about the upcoming dates are present  
      let listSheet = sheets[1];

      // Get all the data in the sheet
      let data = listSheet.getDataRange().getValues();


     // Iterate over all data in the sheet
     for(i = 0; i < data.length; i++) {
        // Get the date of the current row and create a date object
        rowDate = new Date(data[i][0]);
       
        // Get today's date
        today = new Date();

        // Check if the row date is equal to today's date  
        if(rowDate.setHours(0,0,0,0) == today.setHours(0,0,0,0)) {
           
           // If the code reaches here, this row has the date same as today

           // Get the first tab/sheet and then I'm selecting the cells A1, B1 and C1
           // Modify the range as per which cells you want the dish names to be in
           let range = sheets[0].getRange("A1:C1");

           // Set the values of the selected three cells as the value of the second, third and fourth column in the current row of the 2nd tab which are Appetizer, Main dish and Dessert for that date respectively
           range.setValues([[data[i][1], data[i][2], data[i][3]]])
        }
     }
}

这就是您需要的所有代码!保存它,然后您可以尝试单击运行代码,然后检查第一个选项卡以查看更新的值。但是,当您第一次单击运行时,Google 会要求您授予脚本访问工作表的权限。单击查看权限,然后单击您的帐户。然后单击高级,然后单击: .

但是您必须每天运行此代码。这可以使用时间驱动的触发器来实现。

在同一个脚本编辑器窗口中,查看左侧的触发器按钮:

点击屏幕右下角的+ 添加触发器。 并选择如下值(根据需要更改时间):

这就是你所需要的。确保在第二个选项卡中,使用 Excel DATE(YEAR, MONTH, DAY) 函数在日期列中创建日期,而不是手动输入日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多