Excel application not closing from Outlook VBA function

我只是一个虾纸丫 提交于 2019-12-23 19:09:44

问题


I'm writing a sort of homegrown ticketing system for myself in Outlook VBA, and I'm using Excel to store all the persistant data. I have a function written in Outlook to get some data from the .csv and return it. This is all working fine, but after I close the workbook, quit the application, and set the app to nothing I still have an Excel process running! Here is my code:

Private Function GetNewTicketNumber() As Integer
    Dim xlApp As Excel.Application
    Set xlApp = New Excel.Application
    With xlApp
        .Visible = False
        .EnableEvents = False
        .DisplayAlerts = False
    End With
    Dim FileStr As String
    Dim NumberBook As Workbook
    Dim TheRange As Range
    FileStr = "C:\OMGITSAPATH.csv"
    Set NumberBook = Workbooks.Open(FileStr)
    Set TheRange = NumberBook.Worksheets(1).Range("A1")
    GetNewTicketNumber = TheRange.Value
    TheRange.Value = TheRange.Value + 1
    NumberBook.Save
    NumberBook.Close
    xlApp.Quit
    With xlApp
        .Visible = True
        .EnableEvents = True
        .DisplayAlerts = True
    End With

    Set xlApp = Nothing
End Function

Is there something that I'm doing wrong here? My problem is similar to the one here, but I have disabled DisplayAlerts... What can I do to fix this problem?


回答1:


Try fully qualifying your references to Excel, from xl_doesnt_quit

The problem presented here is exactly what you have. This line
Range("a1").Value = Range("a1").Value + 1
leave the xl instance open

The most common cause of the problem is a 'global' reference to the automated application. Unfortunately, under some circumstances it is possible to directly refer to an entity (property/method/object) of the automated object. This reference effectively is global to the calling application. Hence, the reference remains in place as long as the calling program is active. Consequently, the operating system will not end the automated application while the caller is active.

Re-cut code below (which also uses late binding - which rules out the unqualified possibility).

Pls change you path to suit.

code

  Private Function GetNewTicketNumber() As Long
    Dim xlApp As Object
    Dim objWB As Object
    Dim objWs As Object
    Dim FileStr As String

    FileStr = "C:\temp\test.xlsx"

    Set xlApp = CreateObject("excel.application")

    With xlApp
        .EnableEvents = False
        .DisplayAlerts = False
    End With

    Set objWB = xlApp.Workbooks.Open(FileStr)
    Set objWs = objWB.Sheets(1)
    GetNewTicketNumber = objWs.Range("A1")
    objWs.Range("A1") = objWs.Range("A1") + 1

    objWB.Save
    objWB.Close

    Set objWB = Nothing
    xlApp.Quit
    Set xlApp = Nothing
End Function


来源:https://stackoverflow.com/questions/24374763/excel-application-not-closing-from-outlook-vba-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!