Home » excel » vb.net – Randomly occuring COM Exceptions when modifying an Excel Worksheet

vb.net – Randomly occuring COM Exceptions when modifying an Excel Worksheet

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am building an application that generates some data and then outputs it to an Excel sheet. Sometimes this sheet is many thousands of lines long, so I use a BackgroundWorker to deal with it (note that I use a progress bar that prevents editing to stop the user from modifying the spreadsheet while it is being generated).

Unfortunately, while this is happening the program is randomly crashing due to COM exceptions. By randomly I mean that the exceptions occur at different times during execution, and sometimes don’t occur at all. Here is the code causing the issue, the exceptions are always called on the lines using the sheet variable.

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

The exception shows up in different forms including “Return argument has an invalid type.”, “Exception from HRESULT: 0x800A03EC” and a few other HRESULT codes.

Another oddity that might be important – if I catch that exception and then immediately execute the same line, it works. (i.e. the following allows the program to complete successfully)

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

I’ve done quite a bit of hunting around but I cannot figure out how to stop this from happening. The random nature of the exceptions make me think it might be something like the garbage collector which runs at unpredictable times, but I don’t know how to go about testing that theory.

How to&Answers:

I have experienced odd COM exceptions with Excel spreadsheets before and the solution for me was to disable Excel’s autorecover feature. Interop seems to be really picky about being able to get at Excel whenever it wants to and, for me, throws exceptions whenever anything interrupts it.

You can disable autorecover thus:

xlApp.Autorecover.Enabled = False

But remember to enable it again at the end otherwise it will remain off for good.

Not sure if this will fix your issue, but it’s probably worth a try.