创建 post 编辑功能

Creating a post edit function

我目前使用 onEdit 函数来帮助对 sheet 进行排序。 sheet 在 A 列中输入值时进行排序,但我更希望 sheet 在输入 A-F 列中的所有值后进行排序,由于我缺乏编码知识,因此我需要这方面的帮助。

var SORT_COLUMN_INDEX = 2;
var ASCENDING = true;
var NUMBER_OF_HEADER_ROWS = 1;

var activeSheet;

function autoSort(sheet) {
  var range = sheet.getDataRange();

  if (NUMBER_OF_HEADER_ROWS > 0) {
    range = range.offset(NUMBER_OF_HEADER_ROWS, 0);
  }
  range.sort( {
    column: SORT_COLUMN_INDEX,
    ascending: ASCENDING
  } );
}
function onEdit(event) {
  var editedCell;
  activeSheet = SpreadsheetApp.getActiveSheet();
  editedCell = activeSheet.getActiveCell();
  if (editedCell.getColumn() == SORT_COLUMN_INDEX) {
    autoSort(activeSheet);
  }
}

function onOpen(event) {
  activeSheet = SpreadsheetApp.getActiveSheet();
  autoSort(activeSheet);
}

function onInstall(event) {
  onOpen(event);
}

您需要两个列索引

  • a SORT_COLUMN_INDEX 指定 sheet 应按哪一列排序,
  • a TRIGGER_COLUMN_INDEX 指定编辑后应调用哪一列 function autoSort

您可以修改您的代码如下:

var SORT_COLUMN_INDEX = 1;
var TRIGGER_COLUMN_INDEX = 6;
var ASCENDING = true;
var NUMBER_OF_HEADER_ROWS = 1;

var activeSheet;

function autoSort(sheet) {
  var range = sheet.getDataRange();

  if (NUMBER_OF_HEADER_ROWS > 0) {
    range = range.offset(NUMBER_OF_HEADER_ROWS, 0);
  }
  range.sort( {
    column: SORT_COLUMN_INDEX,
    ascending: ASCENDING
  } );
}
function onEdit(event) {
  var editedCell;
  activeSheet = SpreadsheetApp.getActiveSheet();
  editedCell = activeSheet.getActiveCell();
  if (editedCell.getColumn() == TRIGGER_COLUMN_INDEX)  {
    Logger.log('column '+editedCell.getColumn()+' edited');
 autoSort(activeSheet);
  }
  else{
    Logger.log('other column edited');
  }
}

function onOpen(event) {
  activeSheet = SpreadsheetApp.getActiveSheet();
  autoSort(activeSheet);
}

//Sure that you need the following function?
function onInstall(event) {
  onOpen(event);
}