在修改Excel工作表时随机发生COMexception

我正在构build一个生成一些数据的应用程序,然后将其输出到一个Excel工作表。 有时候,这个表单有很多行,所以我使用BackgroundWorker来处理它(请注意,我使用了一个阻止用户修改生成的电子表格的编辑的进度条)。

不幸的是,在发生这种情况时,由于COMexception,程序会随机崩溃。 通过随机我的意思是,exception发生在执行过程中的不同时间,有时根本不会发生。 下面是导致问题的代码,在使用sheetvariables的行上总是调用exception。

 Public Sub modifyCell(ByRef sheet As Worksheet, ByVal row As Integer, ByVal column As Integer, ByRef value As String) sheet.Cells(row, column) = value End Sub Public Sub colorRange(ByRef sheet As Worksheet, ByVal iRow As Integer, ByVal iCol As Integer, ByVal fRow As Integer, ByVal fCol As Integer, ByVal color As Integer, ByRef type As String) If type Is "Interior" Then sheet.Range(sheet.Cells(iRow, iCol), sheet.Cells(fRow, fCol)).Interior.ColorIndex = color ElseIf type Is "Font" Then sheet.Range(sheet.Cells(iRow, iCol), sheet.Cells(fRow, fCol)).Font.ColorIndex = color End If End Sub 

exception以不同的forms出现,包括“返回参数有一个无效types”,“HRESULTexception:0x800A03EC”等几个HRESULT代码。

另一个奇怪的可能是重要的 – 如果我赶上这个例外,然后立即执行相同的行,它的作品。 (即以下允许程序成功完成)

 Try modify sheet code Catch ex As Exception identical modify sheet code End Try 

我已经做了相当多的狩猎,但我不知道如何阻止这种情况的发生。 exception的随机性使我认为它可能像垃圾收集器在不可预知的时间运行,但我不知道如何去testing这个理论。

我以前遇到过Excel电子表格中的奇怪的COMexception,而我的解决scheme是禁用Excel的autorecoverfunction。 Interop似乎对于能够在任何时候想要访问Excel非常挑剔,而且对于我来说,只要有中断事件就会抛出exception。

您可以禁用autorecover:

 xlApp.Autorecover.Enabled = False 

但请记住在最后再次启用它,否则它将保持closures状态。

不知道这是否会解决您的问题,但它可能值得一试。