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

Pau*_*lly 4 office-scripts

我的电子表格中有一个表格,我想删除所有现有数据。我使用下面的代码,除非表格已经为空,否则该代码有效。

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

// Delete all the rows
table.deleteRowsAt(0,rowCount);
Run Code Online (Sandbox Code Playgroud)

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

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

示例:我的表中有 3 行 在此输入图像描述

如果我选择所有行并将它们从表中删除,我会得到以下结果: 在此输入图像描述

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

Sud*_*thy 5

UPDATE:

We now have getRowCount API on the table that you can use to solve this scenario. It'll return the actual rows (not counting the header or expansion row).

    // 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
Run Code Online (Sandbox Code Playgroud)

====

OLD ANSWER

I think we are lacking an API that will provide row count. We'll add that to the backlog. A workaround is this -

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.")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

If row count is 1 and the error code is a specific one that's returned when we delete the 'insert-row', then we can ignore the error. Again, a better approach would be to use an API on the table object to get the row count and delete rows only when row count >= 1. We'll investigate further to improve the experience.