Excel vsto结束编辑模式

时间:2014-03-03 14:05:51

标签: .net excel com vsto

在excel COM插件中我需要访问pageSetup属性。但是如果excel中的编辑模式处于活动状态,我会得到一个例外。

我可以使用以下代码检查编辑模式是否处于活动状态:

CommandBarControl oNewMenu = excelApp.CommandBars["Worksheet Menu Bar"].FindControl(
    1, //the type of item to look for
    18, //the item to look for
    refmissing, //the tag property (in this case missing)
    refmissing, //the visible property (in this case missing)
    true); //we want to look for it recursively so the last argument should be true.

    if ( oNewMenu != null )
    {
        // edit mode = true
        if (!oNewMenu.Enabled) {
        }
    }

我找到了一些退出编辑模式的解决方案,但它们不起作用:

SendKeys.Flush();
excelApplication.SendKeys("{ENTER}");

如何退出编辑模式以便我可以编写pageSetup属性?

1 个答案:

答案 0 :(得分:1)

如果您使用的是加入项,则可以尝试使用它来退出编辑模式:

Globals.ThisAddIn.Application.SendKeys("{ENTER}");

我建议使用与此方法类似的方法来确定Excel是否处于编辑模式:

public static void VerifyExcelIsNotInCellEditMode()
{
    if (Globals.ThisWorkbook.Application.Interactive)
    {
        try
        {
            //Will throw an error if user is editing cell
            Globals.ThisWorkbook.Application.Interactive = false;
            Globals.ThisWorkbook.Application.Interactive = true;
        }
        catch 
        {
            throw new Exception("Excel is in Edit Mode.");
        }
    }
}