Deleting all QueryTables in Excel 2007 Workbook

北战南征 提交于 2020-02-05 06:43:49

问题


Using Excel Interop, I'm attempting to loop through all QueryTables in all Worksheets and delete them. I've got this code, which works:

> // loop through each Worksheet
> for (int i = 1; i <= workbook.Sheets.Count; i++)
> {
>     sheet = (Worksheet)workbook.Sheets.get_Item(i);
> 
>     // loop through each queryTable on each Worksheet
>     int queryTableCount = sheet.QueryTables.Count;
>     for (int j = 1; j <= queryTableCount; j++) {
>        sheet.QueryTables.Item(1).Delete();
>     }
> }

This works just fine for some data connections/files, but for others the "QueryTables.Count" returns zero - even though I know that there are connections. The connections were created in Excel 2007 via the Data tab-->From Other Sources-->From Microsoft Query. Has anyone run into this problem?


回答1:


I figured out the issue, thanks to this post. It turns out that Excel Interop handles query tables differently in the 2003 vs. 2007 versions of Excel. 2007 uses ListObjects, so use the same code to loop through each Worksheet like above, but then use:

// loop through each list object on each Worksheet
if (sheet.ListObjects.Count > 0)
{
   foreach (ListObject obj in sheet.ListObjects)
   {
     obj.QueryTable.Delete();
   }
}


来源:https://stackoverflow.com/questions/5425962/deleting-all-querytables-in-excel-2007-workbook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!