Search code examples
excelwindowsvb.netcom

Unable to cast COM object of type 'System.__ComObject' to class type 'System.Array'


I tried to read excel char with VB.net, I use VS2013 and Office2013

when I used LBOUND and UBOUND function, it cause this exception

the code is :

 Dim objApp As New Excel.Application
 Dim objWorkbook As Excel.Workbook
 Dim objWorksheet As Excel.Worksheet

 objWorkbook = objApp.Workbooks.Open(path & FileName)
 objWorksheet = objWorkbook.Sheets(2)
 area = objWorkSheet.Range("a7", "a8")
 Debug.Print(LBound(area))

and the exception:

未处理System.InvalidCastException HResult=-2147467262
Message=无法将类型为“System.__ComObject”的 COM 对象强制转换为类类型“System.Array”。表示 COM 组件的类型实例不能强制转换为不表示 COM 组件的类型;不过,只要基础 COM 组件支持对接口 IID 的 QueryInterface 调用,就能将这些实例强制转换为接口。

I search the google and not much useful information, so any help is appreciate.


Solution

  • The Range property returns a Range object. To get the value, use the Value or Value2 property of the Range object. The value will be a 2D-array (matrix) when the Range object spans more than one cell. If the Range object only spans a single cell, the value will be a scalar.

    Debug.Print(LBound(area.Value))