gpt4 book ai didi

office-scripts - 如何使用 Office 脚本删除表中的所有行

转载 作者:行者123 更新时间:2023-12-05 01:11:24 26 4
gpt4 key购买 nike

我在电子表格上有一个表格,我想删除所有现有数据。我使用下面的代码,除非表格已经是空的。

// Get the row count
let rowCount = table.getRangeBetweenHeaderAndTotal().getRowCount();

// Delete all the rows
table.deleteRowsAt(0,rowCount);

问题是即使表是空的,rowCount 也会返回 1。当 deleteRowsAt 尝试删除空表中的行时,它会返回错误。

在 VBA 中,我们可以使用 table.ListRows.Count,如果表为空,这将返回 0。

示例:我的表中有 3 行 enter image description here

如果我选择所有行并将它们从表中删除,我会得到: enter image description here

此表现在没有行,但我无法获得此结果。正如我所说,在 VBA 中,我们将使用 table.ListRows.Count,这将返回 0,但我似乎找不到 Office 脚本的等效项。

最佳答案

更新:

我们现在在表上有 getRowCount API,您可以使用它来解决这种情况。它将返回实际行(不包括标题行或扩展行)。

    // Assuming there's a table in the workbook named Table1
let rowCount = workbook.getTable('Table1').getRowCount(); // Table1
// Assuming there's a table in the workbook
let rowCount = workbook.getTables()[0].getRowCount(); // First table

====

旧答案

我认为我们缺少提供行计数的 API。我们会将其添加到积压工作中。解决方法是这样的 -

function main(workbook: ExcelScript.Workbook) {
let table = workbook.getTable("Table26");
let rowCount = table.getRangeBetweenHeaderAndTotal().getRowCount();
try {
table.deleteRowsAt(0, rowCount);
} catch (e) {
if (rowCount === 1 && e.code === 'InvalidArgument') {
console.log("This error means there's no row to delete.")
}
}
}

如果行计数为 1 并且错误代码是我们删除“insert-row”时返回的特定代码,那么我们可以忽略该错误。同样,更好的方法是在表对象上使用 API 来获取行数并仅在行数 >= 1 时删除行。我们将进一步调查以改善体验。

关于office-scripts - 如何使用 Office 脚本删除表中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63250671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com