none
how to close one excel using Process.kill if there are more than one excel workbook opened? RRS feed

  • Question

  • i'm using excel 2013, now i opened 2 excel workbooks(named a.xlsx and b.xlsx respectively) in my pc. 

    I want to using Process.kill() to close a.xlsx, but always failed.

    because i need to find it's windowTitle first, but for excel, if opened more than one excel workbooks, then only one windowTitle of them will be queried by using Process.GetProcessesbyname() etc.

    how can i do?

    thanks.

    Wednesday, December 20, 2017 7:49 AM

Answers

  • You can use Excel Interop.

    Something like this =>

    Excel.Application xlApp = null;
    if (Process.GetProcessesByName("Excel").Count() > 0)
    {
        xlApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application;
        if (xlApp != null)
        {
            foreach (Excel.Workbook wb in xlApp.Workbooks)
            {
                if (wb.Name == "a.xlsx")                             
                    wb.Close();
            }
        }                   
    }
    else
    {
        // Code
    }

    • Marked as answer by imeya Thursday, December 21, 2017 2:04 AM
    Wednesday, December 20, 2017 8:56 AM

All replies

  • Hi imey,

    The proper way to close an excel process is, in you code you need to create an object of you Microsoft Interop Excel and use that object property to kill an excel process like below. See the bold lines in the code. Hope this helps you.

    Microsoft.Office.Interop.Word.Application excl = new  Microsoft.Office.Interop.Word.Application();
    excl.Quit(); //To kill process
    excl = null;
    


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Wednesday, December 20, 2017 8:30 AM
    Moderator
  • You can use Excel Interop.

    Something like this =>

    Excel.Application xlApp = null;
    if (Process.GetProcessesByName("Excel").Count() > 0)
    {
        xlApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application;
        if (xlApp != null)
        {
            foreach (Excel.Workbook wb in xlApp.Workbooks)
            {
                if (wb.Name == "a.xlsx")                             
                    wb.Close();
            }
        }                   
    }
    else
    {
        // Code
    }

    • Marked as answer by imeya Thursday, December 21, 2017 2:04 AM
    Wednesday, December 20, 2017 8:56 AM