2

我需要捕获在我的 Excel 插件中选择的任何一个或多个单元格中包含的值。我目前正在使用 ...ActiveWindow.Selection 和 get_Value() 来一次选择多个单元格和 ...ActiveCell .Value 以获取单个单元格被选中。我的问题是,如果您在单个单元格中输入单个值并单击捕获值的按钮,如果该单元格仍在被编辑(光标仍在单元格中但您已输入值),则所有内容都会返回 null . 有谁知道捕捉这个价值的方法?在尝试输入单个值时,我已经可以看到它是我的用户混淆的根源。

要求澄清:

var selectedCell = Globals.ThisAddIn.Application.ActiveCell.Value;

如果我在此单元格中输入一个值并立即单击按钮,则此值为 null,因为该单元格处于编辑模式而不是选定模式。为了使其工作,我必须单击单元格,然后单击它进行选择。想想一个单元格的不同状态……如果你双击它,它就处于编辑模式。如果单击一次,它将被选中。我想要一个仍处于编辑模式的单元格的值。

4

2 回答 2

3

我们在 VSTO 加载项中遇到了同样的问题。经过大量研究,我们得出结论,VSTO api 无法获取仍处于编辑模式的单元格的值。我们最终破解了以下解决方案:每当按下按钮时,它都会检查 Excel 是否处于编辑模式,如果是,它会弹出一个对话框,告诉用户他们必须在按下按钮之前退出编辑模式。

检查您是否处于编辑模式的代码是:

public bool IsInEditMode()
{
    const int menuItemType = 1;
    const int newMenuId = 18;

    CommandBarControl newMenu =
        Application.CommandBars["Worksheet Menu Bar"].FindControl(menuItemType, newMenuId, Type.Missing, Type.Missing, true);

    return newMenu != null && !newMenu.Enabled;
}

您可以在以下位置查看更多信息:如何判断 Excel 应用程序是否处于单元格编辑模式?

于 2013-06-07T17:49:27.857 回答
0

使用以下 C# 代码退出单元格编辑模式。有用 :

private void exitEditMode()
{
    if (!isExcelInteractive())
    {
        // get the current range
        Excel.Range r = Globals.ThisAddIn.Application.ActiveCell;
        // bring Excel to the foreground, with focus
        // and issue keys to exit the cell
        xlBringToFront();
        Globals.ThisAddIn.Application.ActiveWindow.Activate();
        SendKeys.Flush();
        SendKeys.SendWait("{ENTER}");
        // now make sure the original cell is
        // selected…
        r.Select();
    }
}

private bool isExcelInteractive()
{
    try
    {
        // this line does nothing if Excel is not
        // in edit mode. However, trying to set
        // this property while Excel is in edit
        // cell mdoe will cause an exception
        Globals.ThisAddIn.Application.Interactive = Globals.ThisAddIn.Application.Interactive;
        return true; // no exception, ecel is 
        // interactive
    }
    catch
    {
        return false; // in edit mode
    }
}

private void xlBringToFront()
{
    SetForegroundWindow(Globals.ThisAddIn.Application.Hwnd);
}

[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
于 2014-08-07T11:30:22.077 回答