简体   繁体   English

在VSTO中如何从Excel中的表中删除行

[英]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. 我在Excel工作表中有一张表,需要在其中使用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. 这是通过循环完成的,该循环从表第一行的左列中以“ root”命名的范围开始。
  • 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. 我需要使用“ root”来添加数据,所以不能删除它。
  • 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. 注意 :ThisSheet之前设置为正确的工作表。 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. 可能是由于Excel和VSTO之间的计时问题。

Hope this helps other people! 希望这对其他人有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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