我正在使用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未处理
错误码= -2146827284
的HResult = -2146827284
消息=来自HRESULT的异常:0x800A03EC
我已经检查过,文件肯定会被创建,Excel正在运行,此时已经成功打开了一个工作簿。我根本无法弄清楚这一点,所以任何指针都真的很受欢迎。
更新
文件(tempLocation
)确实存在于正确的位置,但是当我在应用程序外部打开它时,Excel会向我显示“找不到的内容”错误。该文件仍然成功打开,一旦打开就没有问题。我现在可以使用CorruptLoad
方法中的Workbooks.Open()
参数来解决此错误,但我觉得这是盲目地忽略了这个问题。
答案 0 :(得分:4)
如果它有帮助这里是一个简单的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