title: Excel process not closing
body: <p>I've got this C# program that never closes the Excel process. Basically it finds the number of instances a string appears in a range in Excel. I've tried all kinds of things, but it's not working. There is a Form that is calling this method, but that shouldn't change why the process isn't closing. I've looks at suggestions by Hans Passant, but none are working.</p>
  
  <p>EDIT: I tried the things mentioned and it still won't close. Here's my updated code.
  EDIT: Tried the whole Process.Kill() and it works, but it seems like a bit of a hack for something that should just work.</p>
  
  <pre><code>public class CompareHelper
  {
      // Define Variables
      Excel.Application excelApp = null;
      Excel.Workbooks wkbks = null;
      Excel.Workbook wkbk = null;
      Excel.Worksheet wksht = null;
      Dictionary&lt;String, int&gt; map = new Dictionary&lt;String, int&gt;();
  
      // Compare columns
      public void GetCounts(string startrow, string endrow, string columnsin, System.Windows.Forms.TextBox results, string excelFile)
      {
          results.Text = "";
  
          try
          {
              // Create an instance of Microsoft Excel and make it invisible
              excelApp = new Excel.Application();
              excelApp.Visible = false;
  
              // open a Workbook and get the active Worksheet
              wkbks = excelApp.Workbooks;
              wkbk = wkbks.Open(excelFile, Type.Missing, true);
              wksht = wkbk.ActiveSheet;
              ...
  
          }
          catch
          {
              throw;
          }
          finally
          {
              GC.Collect();
              GC.WaitForPendingFinalizers();
  
              if (wksht != null)
              {
                  //wksht.Delete();
                  Marshal.FinalReleaseComObject(wksht);
                  wksht = null;
              }
  
              if (wkbks != null)
              {
                  //wkbks.Close();
                  Marshal.FinalReleaseComObject(wkbks);
                  wkbks = null;
              }
  
              if (wkbk != null)
              {
                  excelApp.DisplayAlerts = false;
                  wkbk.Close(false, Type.Missing, Type.Missing);
                  Marshal.FinalReleaseComObject(wkbk);
                  wkbk = null;
              }
  
              if (excelApp != null)
              {
                  excelApp.Quit();
                  Marshal.FinalReleaseComObject(excelApp);
                  excelApp = null;
              }
  
              GC.Collect();
              GC.WaitForPendingFinalizers();
              GC.Collect();
              GC.WaitForPendingFinalizers();
  
              /*
              Process[] processes = Process.GetProcessesByName("EXCEL");
              foreach (Process p in processes)
              {
                  p.Kill();
              }
              */
          }
      }
  }
  </code></pre>