代码之家  ›  专栏  ›  技术社区  ›  ptownbro

如何使用Microsoft.Office.Interop在Visual Studio中引用Excel NamedRange

  •  0
  • ptownbro  · 技术社区  · 9 年前

    我正在使用ExcelDNA从VBA转换到VB.NET,以实现Excel加载项。在我的代码中,我试图通过NamedRange的名称来引用它(就像在VBA中一样),以设置name的“RefereTo”属性。但是,我得到一个错误,它无法将我提供的名称转换为整数。错误:从字符串“MyNamedRangeName”到类型“Integer”的转换无效。

    在下面的代码中,您可以看到错误发生的位置和原因。

    Imports Microsoft.Office.Interop
    Imports ExcelDna.Integration
    Public Class Class1
        Sub SetReferToProperty()
            Dim ap As Excel.Application = ExcelDnaUtil.Application
            Dim wb as Excel.Workbook = ap.ActiveWorkbook
    
            'This is where the error occurs. Apparently, I can't (?) refer to    
            'the NamedRange by it's name. I need to use it's index.
            wb.Names("MyNamedRangeName").RefersTo = 0
    
            'If I use the Index instead (assume it's 1) it will work, but I
            'want to use the name instead - not the index.
            wb.Names(1).RefersTo = 0
        End Sub
    End Class        
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   Govert    9 年前

    有时(我不确定具体是什么时候)VB.NET要求您指定集合属性(在本例中, Items )显式,默认索引器不工作。所以你需要说:

     wb.Names.Item("MyNamedRangeName").RefersTo = 0
    

    请注意,如果您想添加新名称,您可以说:

    wb.Names.Add("MyNamedRangeName", 0)