获取正在编辑的Excel单元格的值

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

要求澄清:

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

如果我在这个单元格中input一个值,并立即点击button,则此值为空,因为单元格处于编辑模式而不是选定模式。 为了使它工作,我必须点击单元格,然后单击它来select。 想想一个单元格的不同状态…如果你双击它,它处于编辑模式。 如果你点击一次,它被选中。 我想要一个仍处于编辑模式的单元格的值。

我们在VSTO加载项中遇到了同样的问题。 经过大量的研究,我们得出结论:在VSTO API中没有办法获得仍处于编辑模式的单元格的值。 我们结束了以下解决scheme:只要按下button,就会检查Excel是否处于编辑模式,如果是,则popup一个对话框,告诉用户在按下button之前必须退出编辑模式。

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

 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应用程序是否处于单元格编辑模式?

使用以下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);