选择编辑栏并访问 Range.Value 时,C# Excel 加载项异常
我刚刚开始使用带有 VSTO 的 Excel 2010 加载项,很快就被此代码生成的异常所困扰:
public void DoIt()
{
Excel.Range selectedRange = Application.Selection as Excel.Range;
if (selectedRange == null)
{
System.Windows.Forms.MessageBox.Show("Nothing selected");
}
else if(selectedRange.Cells.Count > 0)
{
selectedRange[1, 1].Value = "=2+3"; // exception on this line.
selectedRange[selectedRange.Rows.Count, selectedRange.Columns.Count].Value = "Birthday";
}
}
首先单击工作表中的单个单元格,然后单击公式栏,然后运行上面的代码,可以重现该异常函数(我通过功能区按钮调用它)。
谁能告诉我发生了什么以及如何处理这个异常?感谢您。
I am just starting with Excel 2010 Add-in with VSTO and is quickly stumped by an exception generated by this code:
public void DoIt()
{
Excel.Range selectedRange = Application.Selection as Excel.Range;
if (selectedRange == null)
{
System.Windows.Forms.MessageBox.Show("Nothing selected");
}
else if(selectedRange.Cells.Count > 0)
{
selectedRange[1, 1].Value = "=2+3"; // exception on this line.
selectedRange[selectedRange.Rows.Count, selectedRange.Columns.Count].Value = "Birthday";
}
}
The exception can be reproduced by first clicking on a single cell in the worksheet, then click the formula bar and then run the above function (I call it via a Ribbon button).
Could anyone advise what is happening and how to handle this exception? Thanks you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
例外是因为您无法在公式编辑模式下运行代码。您也无法做很多其他事情。例如,单击编辑栏并单击
Ctrl-N
,这通常会打开一个新工作簿。什么也没发生。我认为您需要捕获异常并退出 Sub,这将模仿正常的 Excel 操作。
理想情况下,您希望禁用该按钮,就像大多数 Excel 功能区按钮在公式编辑模式下一样。我不知道这是否可能。
The exception is because you can't run code while in formula-editing mode. You also can't do quite a few other things. For example, click into the formula bar and click
Ctrl-N
, which normally opens a new workbook. Nothing happens.I think you need to just Catch the exception and exit the Sub, which will mimic normal Excel operation.
Ideally you'd want to disable the button, just like most Excel ribbon buttons are when in formula-editing mode. I don't know if that's possible though.