如何让我的脚本工作- Google Sheets onEdit 脚本

huangapple go评论52阅读模式
英文:

How to get my script works- Google Sheets onEdit script

问题

以下是代码部分的翻译:

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet(); 
  var range = sheet.getRange("A2:E"); 
  range.sort([{column: 1, ascending: true}, {column: 4, ascending: true}]); 
}

如果您需要关于代码的进一步解释或帮助,请随时提问。

英文:

I'm trying to auto-sort by two columns in the range A2:E every time a new line adds to the sheets.

I used this code:

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet(); 
  var range = sheet.getRange("A2:E"); 
  range.sort([{column: 1, ascending: true}, {column: 4, ascending: true}]); 
}

and it works. just one problem
if i got the same "name" (column 1) twice but in a diffrent hour (column 4)
it's first sort it by the name.
what i am trying to do is to devided to groups. that after it's sort it by the column it will sort this "group" by the hour (column 4)

答案1

得分: 1

你可以尝试以下的脚本:

function sortR(e) {
  var t = e.changeType;
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange("A2:E");
  if (t == "INSERT_ROW") {
    range.sort([{column: 1, ascending: true}, {column: 4, ascending: true}]);
  }
}

你的脚本运行正常,但是你的触发器会识别到表格的任何改变,因为你使用的是onChange触发器。如果你想要更加具体的触发条件,你需要使用可安装的onChange触发器。

在测试脚本时,请确保在Google Apps Script UI的触发器部分添加触发器。

触发器设置:

如何让我的脚本工作- Google Sheets onEdit 脚本

参考资料:

英文:

You can try the following script:

function sortR(e) {
  var t = e.changeType;
  var sheet = SpreadsheetApp.getActiveSpreadsheet(); 
  var range = sheet.getRange("A2:E"); 
  if(t == "INSERT_ROW")
  {
    range.sort([{column: 1, ascending: true}, {column: 4, ascending: true}]); 
  }
}

Your script was working fine, however your trigger was recognizing any changes made to the sheet because you had an onChange trigger, but if you want to do it more specific you need to use an onChange trigger which is installable.

When testing the script you need to make sure you add the trigger to the triggers section in the Google Apps Script UI.

Trigger settings:

如何让我的脚本工作- Google Sheets onEdit 脚本

References:

huangapple
  • 本文由 发表于 2023年2月24日 01:17:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定