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?
The
xlworkbook.Worksheets()method returns anExcel.Sheetscollection. Collections (normally) return items of typeObject, and as such, they should be cast to the type you are expecting.As for the
xlworkbook = DirectCast(xlApp.ActiveWorkbook, Excel.Workbook), it appears thisDirectCastmay not be needed, unless the xlApp was created without a reference usingCreateObject("Excel.Application"), which would create an object instead.