如何使用Microsoft.Office.Interop在Visual Studio中引用Excel NamedRange
我正在使用ExcelDNA从VBA转换到VB.NET的Excel加载项。 在我的代码中,我试图通过它的名字来引用一个NamedRange(就像我可以在VBA中)来设置该名称的'ReferTo'属性。 但是,我得到一个错误,它不能转换我提供给一个整数的名称。 错误:从string“MyNamedRangeName”到types“整数”的转换无效。
在下面的代码中,您可以看到错误发生的位置以及原因。
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
有时(我不确定何时)VB.NET要求你显式指定集合属性(在这里是Items
),而默认的索引器不起作用。 所以你需要说:
wb.Names.Item("MyNamedRangeName").RefersTo = 0
请注意,如果你想添加一个新的名字,你会说:
wb.Names.Add("MyNamedRangeName", 0)