0

我的问题是标题中的错误消息:

COM object that has been separated from its underlying RCW cannot be used.

我试图用谷歌搜索它,但我只能找到与析构函数/释放对象相关的解决方案。这不是我想做的事情。

首先,这是我的代码:

String^ filename="c:\\wb.xlsx";
Microsoft::Office::Interop::Excel::Application^ exApp= gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
exApp->Visible=false;
exApp->Workbooks->Open(filename, 2, true, Type::Missing, Type::Missing, Type::Missing, true, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing);
Worksheet^  exWss;
for (int x = 0; x <= checkedListBox1->CheckedItems->Count - 1; x++){
    for (int p=0; p<checkedListBox1->Items->Count; p++){
        if (checkedListBox1->CheckedItems[x]->ToString()->Equals(checkedListBox1->Items[p]->ToString())){
            p++;
            exWss  = safe_cast<Worksheet^> (exApp->ActiveWorkbook->Sheets[p]);
        }
    }
}

简而言之:我有一个选中的列表框,这部分代码在选择了必要的东西后运行。在选中列表框中列出了 Excel 工作簿的不同工作表。我正在尝试根据选中列表框中的所选项目从工作簿中选择工作表。

在最后一行代码 (exWss = safe_cast (exApp->ActiveWorkbook->Sheets[p]);) 我收到了上述错误消息。

我已经看到元帅释放会导致这样的问题。在另一个函数中,虽然我运行 Marshal.Releasecomobject,但它是完全分离的,没有它我也会得到相同的错误。

任何想法,将不胜感激。

4

1 回答 1

0

出于某种原因,“for”块似乎将 Interop 对象与其余代码完全分开。我设法通过在“for”块中初始化 Interop 对象来解决问题。(我引入了一个 bool 变量,指示工作簿是否已经打开 - 如果它是 false,它会在 'for' 块中打开它 - 否则它会继续)

然而有趣的是,该对象可以毫无问题地从“for”块中访问。我相信对此有一个解释,我不知道 - 我是新手,只是爱好程序员。

于 2012-12-30T22:01:42.367 回答