开发者

Deleting all QueryTables in Excel 2007 Workbook

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 tha开发者_运维知识库t 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?


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();
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜