简体   繁体   中英

In VSTO how can I delete rows from a Table in Excel

I have a table in an Excel worksheet where I need to programatically remove entire rows using VSTO. After a lot of searching here and everywhere else, I was unable to find the answer. Due to some unrelated code, I also cannot delete the first row of the table, but need to remove all other rows.

Here are the specific requirements:

  • One of the functions of this addin is to populate the table. This is done through a loop starting with the "root" named range in the left column of the first row of the table.
  • Whenever populating the table, I first need to delete all data from the table and then add the new data. I need to use the "root" to add the data, so I can't have it deleted.
  • I am using the Table for the automated formatting instead of formatting the table manually after adding each cell.
  • I never know how many rows will be added, but it will always be at least one.

After banging my head on this for a few hours, I slept on it and came at it refreshed this morning. After much trial and error, here is the code I came up with.

var deplTable = ThisSheet.Evaluate("DeploymentTable");

if (deplTable.ListObject.ListRows.Count > 1)
    {
        do deplTable.ListObject.ListRows[2].Delete();
            while (deplTable.ListObject.ListRows.Count > 1);
    }

NOTE : ThisSheet is set to the correct sheet earlier. The application works on multiple sheets, so it needs to be flexible.

I tried this a few ways before finally getting it to work. Looping through the rows gave unexpected results; possibly due to timing issues between Excel and VSTO.

Hope this helps other people!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM