选择编辑栏并访问 Range.Value 时,C# Excel 加载项异常

发布于 2025-01-02 00:50:00 字数 630 浏览 2 评论 0原文

我刚刚开始使用带有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

庆幸我还是我 2025-01-09 00:50:00

例外是因为您无法在公式编辑模式下运行代码。您也无法做很多其他事情。例如,单击编辑栏并单击 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文