Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three excel files (MS office 16) opened. My code check for a specific file if it is open then it try to closes it but it closes excel process which ultimately closes all the excel files.

What I noticed is in task manager there is only one EXCEL.EXE porcess for all the files and under Details tab I can see all my open excel file with name.

What I have tried:

C#
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses("Excel");    
  foreach (Process p in processes)
  {
      if (p.MainWindowTitle == "MyFile.xlsx - Excel")
      {
          p.Kill();
          break;
      }
  }

and below code does nothing :

Microsoft.Office.Interop.Excel.Application xlApp = new icrosoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
            //xlWorkbook.Close(false);

            xlWorkbook.Close(true, Type.Missing, Type.Missing);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
            xlWorkbook = null;
            xlApp = null;

            GC.Collect();
Posted
Updated 20-Sep-19 2:39am
v3

1 solution

If you want to check if Excel has already opened files, you have to get an instance of Excel application then loop though the collection of workbooks.

BTW: you need to learn how to use namespace aliases. See: using directive - C# Reference | Microsoft Docs[^]


C#
//on the top of module
using ExcelNs = Microsoft.Office.Interop.Excel;


//then
ExcelNs.Application oExcelApp =  (ExcelNs.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
foreach(ExcelNs.Workbook wbk in oExcelApp.Workbooks)
{
    if(wbk.Name="nameToFind")
    {
        wbk.Close(SaveChanges=false);
    }
}


For further details, please see: Launching Office Apps Programmatically – Andrew Whitechapel[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900