Search code examples
exceloffice-scripts

delete sheet column by table column (object) reference


I am really new to Office Scripts.

I want to delete a sheet columns using reference of a table (object) column.

In VBA, I can try to delete both the table column and the sheet column with this:

    .ListObjects("Table").ListColumns(3).Range.EntireColumn.Delete

Please help me with Office Scripts to delete sheet column with dynamic reference of table column.

When I tried Office Scripts, I could see the deletion separated to 2 deletions: first was deleting of sheet column, second was deleting of table column, even they happened at the same time.

function main(workbook: ExcelScript.Workbook) {
    let selectedSheet = workbook.getActiveWorksheet();
    // Delete range D:D on selectedSheet
    selectedSheet.getRange("D:D").delete(ExcelScript.DeleteShiftDirection.left);
    let Table = workbook.getTable("Table");
    // Delete 1 column(s) at index 3 from table Table
    daily_input_2.getColumns()[3].delete();
}

Solution

  • Your code is close to finish.

    Pls use table1.getColumns() instead of daily_input_2.getColumns(). .getEntireColumn() is equalient to EntireColumn in VBA.

    • Note: OfficeScript uses zero-base index. getColumns()[3] means the 4th column in the table.
    function main(workbook: ExcelScript.Workbook) {
        let table1 = workbook.getTable("Table1");
        // Delete column at index 3 from Table1
        table1.getColumns()[3].getRange().getEntireColumn().delete(ExcelScript.DeleteShiftDirection.left);
    }