VSTO Excel: Fix COMException on Worksheet Activate

A COMException on Worksheet.Activate is a classic VSTO timing issue. Here's the reliable fix.

vsto excel office com csharp fix

The Problem


COMException: The object invoked has disconnected from its clients.
HRESULT: 0x80010108 (RPC_E_DISCONNECTED)

The Fix


Defer access using Application.OnTime, and always release COM objects:


using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

private void ProcessSheetActivation()
{
    Excel.Worksheet? ws = null;
    Excel.Range? range = null;
    try
    {
        ws = (Excel.Worksheet)Application.ActiveSheet;
        range = ws.UsedRange;
        ProcessRange(range);
    }
    finally
    {
        if (range != null) Marshal.ReleaseComObject(range);
        if (ws != null) Marshal.ReleaseComObject(ws);
    }
}