我正在使用ExcelDNA从VBA过渡到VB.NET以获取Excel加载项。在我的代码中,我试图通过它的名称引用NamedRange(就像我在VBA中那样)来设置Name的'ReferTo'属性。但是,我收到一个错误,它无法将我提供的名称转换为Integer。错误:从字符串“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
答案 0 :(得分:1)
有时(我不确定具体到什么时候)VB.NET要求您明确指定集合属性(在本例中为Items
),并且默认索引器不起作用。所以你需要说:
wb.Names.Item("MyNamedRangeName").RefersTo = 0
请注意,如果您想添加新名称,请说:
wb.Names.Add("MyNamedRangeName", 0)