Search code examples
excelvb.nettypesvsto

Type Conversion in VSTO VB.NET from Range to Range?


I have a VSTO Excel project with the following code:

Dim start_row As Integer = 5, start_col As Integer = 1
Dim start_cell As Range = Cells(start_row, start_col)

Hovering the Cells function gives it as a function that returns a Range. However, when building with Option Strict On I get the following build error:

BC30512 Option Strict On disallows implicit conversions from 'Object' to 'Range'.

I can fix this with a DirectCast but I'm confused why the cast is necessary, Cells is supposed to return a Range not an Object.


Solution

  • The Cells property returns Range, but that is not what you are storing in start_cell. If you notice, the Cells property does not accept arguments, and you are supplying two.

    What you are storing in start_cell is the result of indexing the Range object returned by Cells with its indexer, and that returns Object. Essentially, it is

    Dim start_cell As Range = Cells.[_Default](start_row, start_col)
    

    This matches the behaviour of the underlying COM object model.