简体   繁体   English

为什么使用DirectCast分配Excel对象

[英]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. 我在Excel.Interop中使用的所有示例都可以看到DirectCast的用法。 what i dont understand is why we have to use DirectCast here. 我不明白的是为什么我们必须在这里使用DirectCast。 If I declare dim xlworkbook as excel.workbook have using directcast instead of just assigning the workbook? 如果我将dim xlworkbook as excel.workbook声明dim xlworkbook as excel.workbook则使用Directcast而不是仅分配工作簿?

The xlworkbook.Worksheets() method returns an Excel.Sheets collection. xlworkbook.Worksheets()方法返回一个Excel.Sheets集合。 Collections (normally) return items of type Object , and as such, they should be cast to the type you are expecting. 集合(通常)返回类型为Object项目,因此,应将其强制转换为期望的类型。

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. 至于xlworkbook = DirectCast(xlApp.ActiveWorkbook, Excel.Workbook) ,则似乎不需要此DirectCast ,除非xlApp是在没有引用的情况下使用CreateObject("Excel.Application")创建的,该引用将创建一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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