VB.Net Interop Excel Com例外

时间:2015-05-21 13:23:24

标签: vb.net excel com interop

到目前为止,这段代码已经工作了很长时间,

抛出异常:

  

System.InvalidCastException:无法转换类型的COM对象   'System .__ ComObject'到类类型   'Microsoft.Office.Interop.Excel.WorksheetClass'

Dim ds_allJobs As DataSet = DBHandling.searchJob("", "", "all open jobs")
Dim xlApp = New Microsoft.Office.Interop.Excel.Application

xlApp.Visible = False
xlApp.ScreenUpdating = False

Dim xlWorkbook = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
Dim xlWorksheet = New Microsoft.Office.Interop.Excel.Worksheet

xlWorksheet = xlWorkbook.ActiveSheet 'IT FAILS HERE
xlWorksheet.Name = "Open Jobs"    

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

最好指定对象类型(例如exWorkbook As Excel.Workbook

以下是制作新工作表的方法:

'create a new excel application (window)
Dim exApp As New Excel.Application
'add a workbook to it, and take a look at the first worksheet
Dim exWorkbook As Excel.Workbook = exApp.Application.Workbooks.Add()
'create a new worksheet
Dim exWorksheet As Excel.Worksheet
'add this worksheet to the current applicatoin
exWorksheet = CType(exApp.Worksheets.Add(), Excel.Worksheet)

这是否回答了你的问题?最后一行是将对象转换为类型工作表。