![](/img/trans.png)
[英]How can I set an excel cell value to string.empty using interop?
[英]How can I force a cell to stop editing in Excel interop?
我有一個帶有功能區的 Excel 2007 加載項。 功能區中的按鈕之一會觸發對當前工作表的大量操作,出於速度和 UX 原因,我在操作期間將各種Excel.Application
屬性(如Interactive
和EnableEvents
為false
。
我的問題是功能區不會竊取焦點,因此如果用戶在單擊我的功能區按鈕時正在編輯單元格,則在設置Application.Interactive = false
時會引發異常,因為 Excel 認為用戶仍在編輯單元格。
有沒有辦法通過保存或放棄對單元格所做的更改來停止編輯?
看起來Range.DiscardChanges()
可能會解決我的問題,但它在 2007 API 中不可用。
編輯: Range.DiscardChanges()
似乎適用於基於 OLAP 數據源的范圍,因此無論如何它都無法解決我的問題。
編輯:我嘗試在另一個單元格上調用Range.Activate()
。 雖然我確實看到 GUI 中的單元格焦點發生了變化,但無論如何都會拋出異常。 Range.Select()
不做任何事情。
您無法停止編輯,但您可以檢查編輯是否已啟用,然后告訴用戶停止編輯:
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;
}
我在這個頁面找到了答案並將其從 VBA 更改為 C#: https : //www.add-in-express.com/creating-addins-blog/2011/03/23/excel-check-user-edit-cell /
因此,在環顧了幾天並在 MSDN 上詢問之后,最終的答案是 API 中根本沒有任何內容,而且如果不使用 hacky 解決方案1 ,這是不可能的。
Excel 本身處理這種事情的方式只是在用戶編輯時將其菜單灰顯,所以我這樣做是為了與主機應用程序保持一致。
1 : Hacky,因為像使用SendKeys
這樣的技術需要返回到 GUI 以確保操作得到處理,然后調用要求單元格不處於編輯狀態的方法。 這在一個地方很好,但是對 Excel Interop 的每個方法調用都這樣做是瘋狂的。
現在回答它可能為時已晚。 但是認為有人在尋找解決方案時會使用此技巧。
出於某種原因,sendkeys 和 Cells/Range 激活命令沒有鍛煉。
擺脫此問題的唯一解決方法是將焦點更改為另一個工作表並返回到當前工作表以欺騙 excel。 :-)
ExcelUtil.ActivateWorksheet("Sheet1");
currentWorksheet.Activate();
public static void ActivateWorksheet(string strWorksheetName)
{
bool found = false;
foreach (Excel.Worksheet sheet in Globals.ThisAddIn.Application.Worksheets)
{
if (sheet.Name.ToLower() == strWorksheetName.ToLower())
{
found = true;
break;
}
}
if (!found)
Globals.ThisAddIn.AddNewWorksheet(strWorksheetName);
((Excel.Worksheet)Globals.ThisAddIn.Application.Worksheets[strWorksheetName]).Activate();
}
希望這可以幫助。
內存
如果您選擇另一個單元格或所有單元格,錯誤會消失嗎?
private void myFunction() { xlSheet.Cells.Select(); //the rest of the work }
我檢測到問題並顯示一條消息告訴用戶: If excelHelper.ExcelIsEditing() Then System.Media.SystemSounds.Beep.Play() MsgBox("請完成工作表的編輯!" & vbCrLf & vbCrLf & "Move cursor out of當前單元格並再次嘗試按鈕。”) Exit Function End If
函數 ExcelIsEditing() As Boolean ExcelIsEditing = False
If ExcelApp.Interactive = False Then Return False
Try
ExcelApp.Interactive = False
ExcelApp.Interactive = True
Catch
Return True
End Try
結束函數
這是我能想到的最好的:_(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.