VBA Excel不会退出

时间:2013-10-20 15:28:41

标签: excel vba

我遇到的问题是文档有时会导入很好,有时则不会。从它看起来,Excel并不总是关闭。任何人都可以建议一种方法来确保打开的Excel实例已关闭?或者指点我这个很好的参考?我在MS Access中使用此VBA。以下是我的代码:

Public Function ImportPayment()
Dim fd As FileDialog
Dim wb As Workbook
Dim ws As String

Set fd = Application.FileDialog(msoFileDialogFilePicker)
    With fd
    .AllowMultiSelect = False
    .Title = "Please select a file."
    .Show
    On Error GoTo ErrorHandler:
        ws = fd.SelectedItems(1)
        Workbooks.Open (ws)
        Rows("1:9").Select
        Selection.Delete Shift:=xlUp
        Cells(Rows.count, "L").End(xlUp).EntireRow.Delete
        Excel.Application.DisplayAlerts = False
        ActiveWorkbook.SaveAs FileName:= _
        "\\servername\serverfolder\serversubfolder\subfolder\sub\file.txt",
        FileFormat:=xlText _ , CreateBackup:=False
        End With

    ActiveWorkbook.Close
    Excel.Application.DisplayAlerts = True
    Excel.Application.Quit

DoCmd.TransferText acImport, "Specification", "table",
"\\server\serverfolder\serversubfolder\subfolder\sub\file.txt", False
MsgBox ("Your data was imported successfully.")
ImportPayment = Yep
Exit Function

ErrorHandler:
    ImportPayment = Nope
    MsgBox ("The upload was canceled.")

End Function

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

Sub create_excel_instance()

Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Set oExcel = CreateObject("excel.application")

oExcel.Visible = True
set oBook = oExcel.Workbooks.Add

'Close
oBook.close
set oBook = nothing 
oExcel.Quit 

End Sub

注意:您将注意到这段代码设置了对每个对象的引用,而不是使用ActiveWorkbook。这是一种很好的做法;它将为您节省许多错误,并对您创建的对象保持良好的概述。