문제

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 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top