Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force a cell to stop editing in Excel interop?

I have an Excel 2007 add-in with a ribbon. One of the buttons in the ribbon triggers heavy manipulations of the current worksheet and I set various Excel.Application properties like Interactive and EnableEvents to false during the manipulations for speed and UX reasons.

My problem is that the ribbon doesn't steal focus so if the user was editing a cell when he clicks my ribbon button, an exception is thrown when setting Application.Interactive = false because Excel considers the user is still editing the cell.

Is there a way to stop the edition either by saving or discarding the changes made to the cell?

It appears that Range.DiscardChanges() would probably solve my problem but it isn't available in the 2007 API.

EDIT: It seems that Range.DiscardChanges() is for ranges based on OLAP data sources so it wouldn't solve my problem anyway.

EDIT: I have tried calling Range.Activate() on another cell. While I do see the cell focus changing in the GUI, the exception is thrown anyway. Range.Select() doesn't do anything.

like image 464
dee-see Avatar asked Feb 14 '23 11:02

dee-see


2 Answers

So after looking around for a few days and asking on MSDN, the final answer is that there is simply nothing in the API for this and that it isn't possible without using hacky solutions1.

The way Excel itself handles this kind of thing is simply to gray out its menus while the user is editing so I've done that instead for the sake of consistency with the host application.

1: Hacky, because techniques like using SendKeys require going back to the GUI to make sure the action is processed and then calling the method that required the cells to not be in edition. This is fine in one place, but doing that for every method call to the Excel Interop is madness.

like image 185
dee-see Avatar answered Feb 16 '23 01:02

dee-see


You can not stop editing but you can check if editing is enabled and afterwards tell the user to stop it:

private bool IsEditing(Microsoft.Office.Interop.Excel.Application excelApp)
{
    if (excelApp.Interactive)
    {
        try
        {
            excelApp.Interactive = false;
            excelApp.Interactive = true;
        }
        catch (Exception)
        {
            MessageBox.Show("Please stop cell editing before you continue.");
            return true;
        }
    }
    return false;
}

I found the answer at this page and changed it from VBA to C#: https://www.add-in-express.com/creating-addins-blog/2011/03/23/excel-check-user-edit-cell/

like image 21
MrImperial Avatar answered Feb 16 '23 02:02

MrImperial