打开保存的工作簿会导致当前工作簿引发异常 [英] Opening a saved workbook causes the current workbook to throw exceptions

查看:102
本文介绍了打开保存的工作簿会导致当前工作簿引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开一个保存Excel工作簿,同时保留对当前工作簿的引用.问题是,一旦打开保存的工作簿,原始文件就会在访问时引发异常.

I'm trying to open a save Excel workbook while keeping a reference to the current workbook. The issue is that as soon as I open the saved workbook, the original throws an exception upon access.

这是一个代码片段来演示.我将其放在事件处理程序中,以使用功能区按钮对其进行测试.

Here's a code snippet to demonstrate. I put this in an event handler for a ribbon button to test it.

try
{
    string workbookPath = @"C:\Temp\Test.xlsx";
    Workbook current = Globals.ThisAddIn.Application.ActiveWorkbook;
    Workbook newWorkbook = Globals.ThisAddIn.Application.Workbooks.Open(workbookPath);

    current.Activate();                   // throws an exception
    Sheets sheets = current.Worksheets;   // throws an exception
    string name = current.Name;           // throws an exception
}
catch (Exception ex) {}

如果调试并监视currentsheetsname变量,则可以看到,一旦实例化newWorkbook,其他变量在访问时就会引发异常.

If you debug and put watches on the current, sheets and name variables you can see that as soon as newWorkbook is instantiated, the other variables thrown exceptions when accessed.

引发的异常是

System.Runtime.InteropServices.COMException was caught
  Message=Exception from HRESULT: 0x800401A8
  Source=WorkbookTest
  ErrorCode=-2147221080
  StackTrace:
       at Microsoft.Office.Interop.Excel._Workbook.Activate()
       at WorkbookTest.Ribbon1.button1_Click(Object sender, RibbonControlEventArgs e) in C:\Temp\WorkbookTest\WorkbookTest\Ribbon1.cs:line 25
  InnerException: 

最奇怪的是,此发生在新的Excel实例上.如果我打开Excel,请关闭第一个工作簿并打开一个新工作簿,它就可以正常工作.只有当我有一个新打开的Excel实例时,此操作才会失败.我真的不明白为什么.

The strangest thing is that this only happens on a fresh instance of Excel. If I open Excel, close the first workbook and open a new one, it works just fine. It's only if I have a newly opened instance of Excel that this fails. I really don't understand why that is.

有人知道如何解决此问题吗?我在这里做错什么了吗?

Does anyone know how to fix this? Am I doing something wrong here?

推荐答案

我认为这可能是正确的行为.

I think this might be the correct behaviour.

如果您要手动启动一个新的Excel会话(这会自动创建一个新的工作簿[Book1]),然后在不对Book1进行任何操作的情况下打开现有的工作簿,您会注意到Book1在Excel会话中不再存在

If you were to manually start a new Excel session (which automatically creates a new workbook [Book1]) and then, without doing anything to Book1 open an existing workbook, you'll notice that Book1 no longer exists in the Excel session.

我猜您通过C#加载项也遇到了相同的行为.

I'm guessing you're experiencing the same behaviour via your C# add-in.

这篇关于打开保存的工作簿会导致当前工作簿引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆