Google Sheets 脚本用于根据多列自动对表格进行排序 - 错误

问题描述 投票:0回答:1

我正在尝试编写一个 Google Sheets 脚本,用于根据多列自动对表格进行排序。我让自动排序开始工作,然后决定仅当到达每行的第 6 列时才更新工作表。这样,新行就不会随着每个条目而更新并疯狂移动。相反,一旦填充完成就会对其进行排序。但是,该表未成功更新。完成这项工作后,我还想将该规则应用于 individual02 工作表,以便在更新该工作表时它也会自动排序,并且也希望在这一步中得到一些帮助。我是一个超级初学者,所以学到了很多东西,我感谢所有的帮助。

这是该表的链接,如果您想创建一个副本来运行测试:text

**这是我的脚本,有人有什么建议吗? **

// created this first part so that the values can be easily changed as they are referenced in the Part 02, where the function is. This way I could share the Script with other people and all they would have to do is change this first part's values to match their own table.

// Part 01 - Defining Variables:

var SHEET_NAME = "Individual01"

var DATA_RANGE = "A2:G999" // from Column A Row 2 (excluding top row bc it is the header) to Column G row 999 

var SORT_ORDER = [
{column: 3, ascending: true}, // sorted by Category
{column: 4, ascending: true}, // then sorted by Status
{column: 5, ascending: true}, // then sorted by Priority
{column: 1, ascending: true}, // then sorted by Title
{column: 6, ascending: true} // then sorted by Together?
]  // ascending order = true, and descending order = false

var SORT_COLUMN_NUMBER = "6" // function will be activated after the cell in this column is filled
var FIRST_ROW_AFTER_HEADER = "2"


//________________________________________________________________________//
// Part 02 - Writing the Function for Multi Sorting Columns:


// Part 02-a
function autoSortMultiColumns(e){
  
  
    const row = e.range.getRow() // saving the row value from our range
    const column = e.range.getColumn() // saving the column value from our range
    const ss = e.source // spread sheet
    const currentSheet = ss.getActiveSheet()
    const currentSheetName = currentSheet.getSheetName

    if (!(currentSheetName === "SHEET_NAME" && column === SORT_COLUMN_NUMBER && row >= FIRST_ROW_AFTER_HEADER)) return 
    // The update will only happen after the sort column has been filled.

    const range = currentSheet.getRange(DATA_RANGE)
    
    range.sort(SORT_ORDER) // uses the variable defined in part 01

    ss.toast('Sort complete.')
}


// Part 02-b
function onEdit(e){ // onEdit(event)special function that runs everytime something changes in your spreadsheet

  
  autoSortMultiColumns(e) 

}


javascript google-sheets google-apps-script
1个回答
0
投票

使用可安装的 onEdit 触发器:

function onMyEdit(e) {
  const sh = e.range.getSheet();
  if (!(sh.getName() == "Individual01" && e.range.columnStart == 6 && e.range.rowStart > 1)) {
    sh.getRange("A2:G999").sort([{ column: 3, ascending: true }, { column: 4, ascending: true }, { column: 5, ascending: true }, { column: 1, ascending: true }{ column: 6, ascending: true }])
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.