我想檢查一個單元格是否包含名稱或是一個命名範圍,如果沒有,我將分配一個名稱。這裏是我的代碼:C#Excel檢查單元格在VSTO中包含一個名稱
if (cell.Name.Name == null)
{
Globals.ThisWorkbook.Names.Add("Temp", cell);
}
else
{
// Move on
}
然而,上面的代碼將拋出一個COMException
。相反,我試圖這樣做是爲了避開它:
try
{
if (cell.Name.Name == null) { }
}
catch (COMException)
{
Globals.ThisWorkbook.Names.Add("Temp", cell);
}
的第二代碼片段的工作,但我的電子表格正在一個嚴重的性能問題。操作從約80毫秒到1700毫秒。這可能看起來不多,但我正在循環選擇範圍。
錯誤消息是:
System.Runtime.InteropServices.COMException was unhandled by user code
HResult=-2146827284
Message=Exception from HRESULT: 0x800A03EC
Source=""
ErrorCode=-2146827284
StackTrace:
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Range.get_Name()
at ExcelTemplate1.Sheet1.button2_Click(Object sender, EventArgs e) in c:\Users\User\Desktop\ExcelTemplate1\ExcelTemplate1\Sheet1.cs:line 116
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
InnerException:
問題是,是否有更好的方法來檢查細胞命名的範圍?
請參閱上面的修改後的命名。至於性能,只需要很長時間才能完成大量的單元。 – Keylee 2015-02-11 23:14:09