Excel 与 VB.NET(来自 HRESULT 的异常:0x8002000B (DISP_E_BADINDEX))
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14665903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel with VB.NET (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
提问by Mouhcine Benmeziane
I'm trying to create an Excel file from VB.net from my first time. I already added the Microsoft.Office.Excel reference, Import the Microsoft.Office.Interop
我第一次尝试从 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
The error generetad is in the line :
错误generetad在行中:
xlWorkSheet = CType(xlWorkBook.Sheets("sheet1"), Excel.Worksheet)
Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
回答by Hans Passant
Maybe your version of Excel doesn't speak English. And "sheet" is a dirty word in the local language, it kinda is in English ;) Your name is a hint that English is not the default language. Use the index instead of the name to avoid accidents like this:
也许您的 Excel 版本不会说英语。而“sheet”在当地语言中是一个脏词,有点像英语;) 你的名字暗示英语不是默认语言。使用索引而不是名称来避免这样的事故:
xlWorkSheet = CType(xlWorkBook.Sheets(1), Excel.Worksheet)
回答by UrsulRosu
This could also be happening because
这也可能发生,因为
Workbook.Worksheets.Count
is less than the number of sheets you use, depending on how your Excel settings are. For me it starts with 3 sheets but for a colleague it starts with 2 sheets.
少于您使用的工作表数量,具体取决于您的 Excel 设置。对我来说,它从 3 张开始,但对于同事来说,它从 2 张开始。
So you can call
所以你可以打电话
Workbook.Worksheets.Add()
to reach the desired number of sheets
达到所需的张数