vb.netexcel-interopdirectcast

Why using DirectCast assigning Excel Objects


I am struggeling with understanding the following code

Dim _xlsSheet As Excel.Worksheet = DirectCast(xlworkbook.Worksheets(Name), Excel.Worksheet)

or

xlworkbook = DirectCast(xlApp.ActiveWorkbook, Excel.Workbook)

All examples I work throu concerning Excel.Interop I see the use of DirectCast everywhere. what i dont understand is why we have to use DirectCast here. If I declare dim xlworkbook as excel.workbook have using directcast instead of just assigning the workbook?


Solution

  • The xlworkbook.Worksheets() method returns an Excel.Sheets collection. Collections (normally) return items of type Object, and as such, they should be cast to the type you are expecting.

    As for the xlworkbook = DirectCast(xlApp.ActiveWorkbook, Excel.Workbook), it appears this DirectCast may not be needed, unless the xlApp was created without a reference using CreateObject("Excel.Application"), which would create an object instead.