c++ - COM object that has been separated from its underlying RCW cannot be used

My problem is the error message in the title:

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

I have tried to google it, but i could find only solutions related to destructors/releasing objects. It is not something i want to do.

First, here is my code:

String^ filename="c:\\wb.xlsx";
Microsoft::Office::Interop::Excel::Application^ exApp= gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
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())){
            exWss  = safe_cast<Worksheet^> (exApp->ActiveWorkbook->Sheets[p]);

In short: i have a checkedlistbox, this part of code is ran when the necessary stuff have been selected. In the checkedlistbox the different sheets of the Excel workbook are listed. I am trying to select the sheet from the workbook according to the selected item in the checkedlistbox.

At the last code line (exWss = safe_cast (exApp->ActiveWorkbook->Sheets[p]);) I get the mentioned error message.

I have seen that Marshal releasing can cause such problems. In another function although i run Marshal.Releasecomobject, but it is completely separated, and i get the same error without it also.

Any ideas would be appreciated.


It seems for some reason the 'for' block separates completely the Interop object from the rest of the code. I managed to solve the problem by initializing the Interop object within the 'for' block. (I have introduced a bool variable, indicating if the workbook has been opened already - if it is false, it opens it within the 'for' block - otherwise it continues)

Interestingly however the object is accessible out of the 'for' block without a problem. I am sure there is an explanation for that, that i do not know - I am newbie, hobby programmer only.

Need Your Help

Running vi within a bash script and executing vi commands to edit another file

bash shell terminal editor vi

So I've made a script which is collecting data from many different files:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.