Google INSERT_COLUMN 的 Sheets App Script onChange(event):如何获取插入的列?

Google Sheets App Script onChange(event) for INSERT_COLUMN: how to get which column was inserted?

function onInsertColumn(activeRng) {  
  /* I coded this function, and it works, so I'll omit 
  the implementation here because it's irrelevant. 
  But I haven't figured out how to get the active range
  from the onChange event (to pass to this function).*/
}

function onChange(event) {
  // 
  // 
  // https://developers.google.com/apps-script/guides/triggers/installable#google_apps_triggers
  // https://developers.google.com/apps-script/guides/triggers/events
   
  if(event.changeType == 'INSERT_COLUMN'){
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const sheet = ss.getActiveSheet()
    const activeRng = sheet.getSelection().getActiveRange(); // WHAT SHOULD GO HERE?
    onInsertColumn(activeRng);
  }
}

解释:

正如用户已经在评论中提到的,这取决于列的插入方式。如果这是通过电子表格手动完成的 UI 那么您可以获得所选的活动列的编号:

const colNumber = sheet.getSelection().getActiveRange().getColumn();

然后创建一个 range 对象来代表整个列范围:

const activeRng = sheet.getRange(1,colNumber,sheet.getMaxRows(),1);

然后您可以将此范围提供给任何函数。

当然,除了 getMaxRows(),您还可以使用 getLastRow() 来获取内容直到最后一行,而不是整个列范围。

手动插入列时的解决方法:

function onInsertColumn(activeRng) {  
  // example
  activeRng.setValue("Selected");
}


function onChange(event) {
  // 
  // 
  // https://developers.google.com/apps-script/guides/triggers/installable#google_apps_triggers
  // https://developers.google.com/apps-script/guides/triggers/events
   
  if(event.changeType == 'INSERT_COLUMN'){
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const sheet = ss.getActiveSheet();
    const colNumber = sheet.getSelection().getActiveRange().getColumn();
    const activeRng = sheet.getRange(1,colNumber,sheet.getMaxRows(),1);
    onInsertColumn(activeRng);
  }
}