2016-03-06 28 views
0

我正在使用ExcelDNA從Excel轉換到Excel加載項,從VBA轉換爲VB.NET。在我的代碼中,我試圖通過它的名字來引用NamedRange(就像我可以在VBA中)來設置該名稱的'ReferTo'屬性。但是,我收到一個錯誤,它無法將我提供給Integer的名稱進行轉換。錯誤:從字符串「MyNamedRangeName」轉換爲鍵入「整數」無效。如何使用Microsoft.Office.Interop在Visual Studio中引用Excel NamedRange

在下面的代碼中,您可以看到發生錯誤的位置以及原因。

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

有時候,(我不知道什麼時候)VB.NET需要你明確指定集合屬性(在這種情況下,Items),而默認索引不起作用。所以,你需要說:

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

注意,如果你想添加一個新的名字,你會說:你是無處不在

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

哇霍弗特! =)解決了它。謝謝你的幫助。 – ptownbro

相關問題