建立 Excel 腳本來刪除行

建立 Excel 腳本來刪除行

我正在使用 Excel Online 中的新腳本功能(不是 VBA)與 Power Automate 結合使用。我正在嘗試創建一個在給定點之後刪除行的腳本。最初,它有效,但後來我不斷收到錯誤。

我使用過以下函數:

  1. getRangeEdge(方向,activeCell),
  2. 取得行索引(),
  3. getHeaderRowRange()
  4. 刪除行數(索引,計數)

我的最終腳本是:

function main(workbook: ExcelScript.Workbook) {
  // [Directly from link 1]
  // Get the current worksheet.
  let selectedSheet = workbook.getActiveWorksheet();

  // [Directly from link 3]
  // Get the first table on the current worksheet.
  const currentSheet = workbook.getActiveWorksheet();
  const table = currentSheet.getTables()[0];

  // [Directly from link 1]
  // Get the last used cell at the end of the column.
  // This recreates the Ctrl+Down arrow key behavior.
  let firstCell = selectedSheet.getRange("A1");
  let firstColumn = selectedSheet.getRange("A1").getRangeEdge(ExcelScript.KeyboardDirection.down);
  let cellAfter = firstColumn.getOffsetRange(1, 0);

  // [My own creation using link 2]
  // Saves the row number of the cell after the Ctrl+Down
  let FinalRow = cellAfter.getRowIndex();

  // [My own creation using link 4]
  // Deletes all rows from the last row for 2000 rows.
  // Without '-1' a blank row is left. '-1' deletes all the empty rows.
  table.deleteRowsAt(FinalRow - 1,2000);

}

當我第一次運行腳本時,我沒有遇到任何問題並且它可以工作。第二次運行該腳本時,它起作用了,但我收到一條錯誤訊息「第 25 行:表 deleteRowsAt:參數無效或遺失或格式不正確。」。刷新後,我相信,我遇到了第三個問題,其中腳本在“ExcelScript”處給我一個錯誤 - 但可以工作並給我“第 25 行...”錯誤。截圖如下。

顯示「ExcelScript」和「第 25 行...」錯誤的腳本“腳本顯示“ExcelScript”和“第 25 行...”錯誤”

相同的程式碼,但沒有註釋“相同的程式碼,但沒有註解”

我需要它正常運行,因為當我將它添加到我的 Power Automate 流程時,錯誤會導致它中斷。

我確實意識到,即使“工作”腳本提供錯誤,我也可以在 Power Automate 中配置“之後運行”以繼續。但是,當透過 Power Automate 運行腳本時,它無法“工作”,即使透過 Excel Online 運行腳本可以“工作”。

我很感謝你的幫忙。

相關內容