使用VB.NET的Excel(来自HRESULT的异常:0x8002000B(DISP_E_BADINDEX))

时间:2013-02-02 20:00:06

标签: vb.net excel

我第一次尝试从VB.net创建Excel文件。 我已经添加了Microsoft.Office.Excel引用,导入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

错误generetad在行:

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

   Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))

2 个答案:

答案 0 :(得分:10)

也许您的Excel版本不会说英语。而“表格”是当地语言中的脏词,它有点英文;)你的名字暗示英语不是默认语言。使用索引而不是名称来避免这样的事故:

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

答案 1 :(得分:2)

这也可能发生,因为

Workbook.Worksheets.Count

小于您使用的纸张数量,具体取决于Excel设置的方式。对我来说,它从3张纸开始,但对于同事来说,它开始了 有2张。

所以你可以打电话给

Workbook.Worksheets.Add()

达到所需的张数