简体   繁体   English

Excel Interop:从特定工作簿获取命名表(范围)

[英]Excel Interop: Get named table (Range) from specific workbook

I'm trying to create a WinForms application that interacts with Excel using the Excel Object Library v.15. 我正在尝试创建一个使用Excel对象库v.15与Excel进行交互的WinForms应用程序。

I'm using this to get the Excel Application object 我正在使用它来获取Excel Application对象

(Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

And I know I can get the Range for the named table I want by using 我知道我可以通过使用获取想要的命名表的范围

_application.Range["MyTableName"];

Now, the problem I'm facing is that if I have two workbooks opened at the same time and each one of them has a named table with the same name, I don't know which Range will be returned. 现在,我面临的问题是,如果我同时打开了两个工作簿,并且每个工作簿都有一个具有相同名称的命名表,则我不知道将返回哪个Range。

The Excel application is unique, so I cannot simply try to get the process based on the window title or something like that. Excel应用程序是唯一的,因此我不能简单地尝试基于窗口标题或类似的东西来获得该过程。 I can get the Workbook object based on its title: 我可以根据其标题获取Workbook对象:

_application.Workbooks.Cast<Workbook>().FirstOrDefault(w.Name.Equals(title))

However I cannot access the Ranges of a particular Workbook. 但是,我无法访问特定工作簿的范围。 I know I could iterate through the Sheets of the Workbook element trying to find the table but I was wondering if there was another "cleaner" way. 我知道我可以遍历“工作簿”的“表格”以尝试查找表格,但是我想知道是否还有另一种“更清洁”的方式。

I would appreciate any guideline on this. 我对此表示任何指导。

Thanks, 谢谢,

  • Will

The simplest/most direct way I can think of would be to iterate through the Names collection , check the parent, and move on. 我想到的最简单/最直接的方法是遍历Names集合 ,检查父级并继续。

Eg: 例如:

For Each NamedRange as Range in MyApplication.Names
    Dim Check as Object = TryCast(NamedRange.Parent, Workbook)
    If Check Is Nothing Then 
        Check = TryCast(NamedRange.Parent, Worksheet)
        Check = TryCast(Check.Parent, Workbook) 
    End If

    If Not Check Is Nothing AndAlso Check.Name = "MyWorkbook" Then 
        'Do something
    End If
Next

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

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