ComException当尝试从C#中的Excel文件中删除工作表时 [英] ComException When trying to delete a worksheet from an Excel File in C#

查看:77
本文介绍了ComException当尝试从C#中的Excel文件中删除工作表时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题,似乎无法解决.我试图删除包含特定工作表名称的工作簿中的任何工作表,但我不断收到此异常:无法获取Worksheet类的Delete属性",我可以在其他地方使用该工作表类,但当我尝试使用Delete()时;方法,甚至是设置所述工作表可见性的方法,我都会得到相同的结果.任何帮助,为什么将不胜感激!

I'm running into an Odd problem that I cant seem to find a solution for. I'm trying to delete any work sheet in a workbook that contains a certain worksheet name and I keep getting this exception: "Unable to get the Delete property of the Worksheet class" I'm able to use the worksheet class in other places but when i try to use the Delete(); method, or even the one that sets the visibility of said sheet I get the same thing. Any help as to why would be appreciated!

Microsoft.Office.Interop.Excel.Sheets TestWorksheets = TestBook.Worksheets;
if (TestWorksheets.Count > NumberofsheetsIWantToKeep)
{
   int WorkSheetCounter = TestWorksheets.Count;
   while (WorkSheetCounter > NumberofsheetsIWantToKeep)
   {
      if(TestWorksheets[WorkSheetCounter].Name.Contains("blah"))
      {
        TestWorksheets[WorkSheetCounter].Delete();
      }
      WorkSheetCounter--;
   }
}

推荐答案

原来,我必须先激活工作簿和工作表,然后才能删除它.我为此感到愚蠢,并为此道歉!

turns out I had to activate the workbook and the worksheet before I could delete it. I feel silly and apologize for that!

这篇关于ComException当尝试从C#中的Excel文件中删除工作表时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆