有没有办法按数字/相反方向对这个 Google 脚本函数进行排序? [英] Is there a way to sort this Google scripts function numerically/opposite direction?

本文介绍了有没有办法按数字/相反方向对这个 Google 脚本函数进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来将 Google 表格文档的所有表格名称拉入首页列表中的脚本.这是工作;但是,有没有办法以相反的方式对此进行排序?我有按日期命名的工作表,最旧的日期作为最远的工作表,最新的工作表最靠近前面.所以它首先对最新的日期进行排序,但我希望它首先对最旧的日期进行排序.另外,有没有办法使这个函数动态化,以便它随着新工作表的添加或工作表名称的变化而更新?

Here is the script that I'm using to pull all the sheet names of a Google Sheet Document into a list on a front sheet. It is working; however, is there a way to sort this the opposite way? I have the sheets named by date with the oldest date as the furthest sheet and the newest sheet the closest to the front. So it is sorting the newest date first but I would like it to sort with the oldest date first. Also, is there a way to make this function dynamic so it updates as new sheets are added or if the sheet names change?

function sheetnames() {
  var out = new Array()
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();


for (var i=0 ; i<sheets.length ; i++) {
  Logger.log(String(sheets[i].getSheetId()));
 // var sheetId = sheets.getSheetId()
  out.push( [ sheets[i].getName() ] ) 
}

return out 
}

推荐答案

您可以使用 onChange 可安装触发器,但要考虑其限制.这样,我将为您提供的代码,每次添加新工作表或编辑工作表名称时都会运行:

You could use an onChange Installable Trigger, but take into consideration its Restrictions. In this way, the code I will be providing you, it will run every time you add a new sheet or you edit a sheet's name:

// Installable Trigger
function onChange() {
  var dates = sheetNames();
  Logger.log(dates);
}

function sheetNames(){
  try{
    // Get all sheets and then return
    return SpreadsheetApp.getActiveSpreadsheet()
             .getSheets()
             // Get a new array only with the sheet names
             .map(function(sheet){ return sheet.getName() })
             // Sort the array from the oldest date to the newest date
             .sort(
               function (sheet1, sheet2){
                 return new Date(sheet2) - new Date(sheet1);
               });
  } catch(e){
    Logger.log("Not a date");
    return e;
  }
}

现在,要设置可安装触发器,请执行以下操作:

Now, for setting up the installable trigger, do the following:

1) 转到您的 Apps 脚本项目

1) Go to your Apps Script project

2) 点击编辑->当前项目的触发器

2) Click Edit->Current project's triggers

3) 点击+添加触发器"

3) Click "+ Add Trigger"

4) 选择:

选择要运行的函数 ->

Choose which function to run ->

选择事件源->来自电子表格

Select event source-> From spreadsheet

选择事件类型 -> 更改时

Select event type -> On change

5) 点击保存

这篇关于有没有办法按数字/相反方向对这个 Google 脚本函数进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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