简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM