excel Office脚本-如何i)删除列和ii)根据列标题查找列的小计?

elcex8rz  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(105)

我正在尝试使用Office脚本i)删除标题名为“对象类型”的列,ii)对名为“命中次数”的列中的单元格(所有可见的筛选单元格)求和。
我是Office Script的新手,遇到了问题。getColumnByName出现以下错误:无法读取未定义的属性(阅读“getColumnByName”)
任何帮助都将不胜感激!

let selectedSheet = workbook.getActiveWorksheet();

  let table = workbook.getTables()[0];

//delete a column with a header named "Object Type"
 let rangeObj = table.getColumnByName("Object_Type").getRange();
  selectedSheet.getRange(rangeObj).delete(ExcelScript.DeleteShiftDirection.left);

//Sum up the cells  (all the visible filtered cells) in the column named "Hits"
  let rangeHits = table.getColumnByName("Hits").getRange();
  ??? (How to get subtotal based on range selected?)

}
cbjzeqam

cbjzeqam1#

如果你试图在一个不存在的列上使用getColumnByName(例如,因为它已经被删除),你会得到一个错误。如果你在文件中有多个表,并且workbook.getTables()[0]返回了错误的表,你也会得到这个错误。
出于我的目的,我假设代码抛出错误是因为代码之前已经运行过,而不是因为引用了错误的表。如果这不正确,请告诉我,我可以调整代码。您可以看到下面的代码:

function main(workbook: ExcelScript.Workbook) {
      let selectedSheet = workbook.getActiveWorksheet();
    
      let table = workbook.getTables()[0];
    
      //delete a column with a header named "Object Type"
    
      //added optional chaining so that this line doesn't throw
      //an error if the column has previously been deleted
      table.getColumnByName("Object_Type")?.delete()
    
      //shows the total row for the table
      table.setShowTotals(true)
    
      //sets the rangeHits variable to the rangeHits column in the table
      let rangeHits = table.getColumnByName("Hits");
    
    //Sum up the cells  (all the visible filtered cells) in the column named "Hits"
      rangeHits.getTotalRowRange().setFormulaLocal(`=SUBTOTAL(109,${rangeHits.getRangeBetweenHeaderAndTotal().getAddress()}`)
    }

相关问题