VB.NET Excel Program Leaves EXCEL.EXE floating after completion

前端 未结 4 1855
醉酒成梦
醉酒成梦 2020-12-04 01:51

I am writing a program that loops through all of the sheets in an Excel workbook and saves each sheet as its own workbook. It turned out to be a bit trickier than I expected

4条回答
  •  孤城傲影
    2020-12-04 02:34

    The solution I finally came across was to add

    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp1.ActiveWorkbook)
    xlApp1.ActiveWorkbook.Close()
    

    to the loop. I found this answer in the comments of The first answer on another stack overflow post. Basically, the problem I was having is that the worksheet.copy method creates a workbook object with no reference, but it turns out it can be referenced by referring to the activesheet. If you wanted to do more with it than just kick it out the door like I am, I imagine you could create a new workbook object and assign it or as the post I link to suggests, you can save it as something as well. For my puposes, it is just fine to release it after saving the worksheet I want and this removed my excel.exe hanging process.

    If you want a bit more elgant code option you should check out the ron tornambe post where he does the for each loop I managed to not get right instead of the wonky thing I create. Basically you would want to use his loop in my code and you would have it all set up. Thanks as always stack overflow.

提交回复
热议问题