Excel with VB.NET (exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))

I am trying to create an Excel file with VB.net the first time. I already added the link Microsoft.Office.Excel, imports Microsoft.Office.Interop

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value

    xlApp = New Excel.ApplicationClass
    xlWorkBook = xlApp.Workbooks.Add(misValue)
    xlWorkSheet = CType(xlWorkBook.Sheets("sheet1"), Excel.Worksheet)
    xlWorkSheet.Cells(1, 1) = "Something here"
    xlWorkSheet.SaveAs("D:\vbexcel.xlsx")

    xlWorkBook.Close()
    xlApp.Quit()
    releaseObject(xlApp)
    releaseObject(xlWorkBook)
    releaseObject(xlWorkSheet)

    MsgBox("Excel file created , you can find the file c:\")

End Sub

The error generator is in the line:

   xlWorkSheet = CType(xlWorkBook.Sheets("sheet1"), Excel.Worksheet)

   Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
+5
source share
2 answers

Your version of Excel may not speak English. And "sheet" is a dirty word in the local language, it looks like English;) Your name is a hint that English is not the default language. Use an index instead of a name to avoid such accidents:

    xlWorkSheet = CType(xlWorkBook.Sheets(1), Excel.Worksheet)
+8
source

It can also happen because

Workbook.Worksheets.Count

, Excel. 3 , 2 .

,

Workbook.Worksheets.Add()

+2

All Articles