vb.net – WinForms COM Exception打开Excel工作簿

前端之家收集整理的这篇文章主要介绍了vb.net – WinForms COM Exception打开Excel工作簿前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用VB.Net编写一个非常基本的WinForms应用程序,一切顺利,直到我尝试打开我通过Stream对象写入tempLocation的Excel文件(工作簿在我的项目资源和构建操作中)设置为“嵌入式资源”)

这是导致错误代码

Dim xlWBTemp As Excel.Workbook
Dim xlApp As Excel.Application
'// Below resolves to "C:\Users\MacroMan\LockTemplate.xlsm"
Dim tempLocation As String = Environ("USERPROFILE") & "\LockTemplate.xlsm"
...
xlWBTemp = xlApp.Workbooks.Open(tempLocation) '<~~ error here.

我得到的错误是:

System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2146827284
HResult=-2146827284
Message=Exception from HRESULT: 0x800A03EC

我已经检查过,文件肯定会被创建,Excel正在运行,此时已经成功打开了一个工作簿.我根本无法弄清楚这一点,所以任何指针都真的很受欢迎.

更新:

文件(tempLocation)确实存在于正确的位置,但是当我在应用程序外部打开它时,Excel会给出“找不到的内容错误.该文件仍然成功打开,一旦打开就没有问题.我现在可以通过使用Workbooks.Open()方法中的CorruptLoad参数来解决错误,但我觉得这是盲目地忽略了这个问题.

如果它有帮助这里是一个简单的VB.NET应用程序的例子,我很久以前写的测试VB与C#的速度.这是创建工作簿并写入工作簿的另一种方式.
Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

    Private Sub Button1_Click(sender As System.Object,e As System.EventArgs) Handles Button1.Click
        Dim xlApp As New Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value

        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkBook.Application.Visible = True
        xlWorkBook.Application.ScreenUpdating = False

        xlWorkSheet = xlWorkBook.Sheets("sheet1")
        xlWorkSheet.SaveAs("C:\\vbexcel.xlsx")

        Dim l As Long
        l = 1
        Do While l < 500
            'xlWorkSheet.Cells(l,1) = l
            xlWorkSheet.Range("A" & l).Value = l
            'xlWorkSheet.Cells(l,2) = l
            'xlWorkSheet.Cells(l,3) = l
            l = l + 1
        Loop

        xlWorkBook.Application.ScreenUpdating = True
        xlWorkBook.RefreshAll()
        xlWorkBook.Save()

        'xlWorkBook.Close()
        'xlApp.Quit()

        releaSEObject(xlApp)
        releaSEObject(xlWorkBook)
        releaSEObject(xlWorkSheet)

        MsgBox("Done")
    End Sub

    Private Sub releaSEObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub
End Class
原文链接:https://www.f2er.com/vb/255610.html

猜你在找的VB相关文章