Ans*_*Ans 3 excel vba excel-vba
我有一个应用程序,首先创建一个不可见的应用程序:
Dim ExcelApp As Object
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Visible = False
ExcelApp.ScreenUpdating = False
ExcelApp.DisplayAlerts = False
ExcelApp.EnableEvents = False
Run Code Online (Sandbox Code Playgroud)
然后继续用它来隐形地打开文件:
Do While fileTitle <> ""
Dim dataWorkbook As Workbook
Set dataWorkbook = ExcelApp.Application.Workbooks.Open(folderPath & fileTitle)
Run Code Online (Sandbox Code Playgroud)
在使用文件宏的操作结束时关闭文件:
dataWorkbook.Close
fileTitle = Dir()
Loop
Run Code Online (Sandbox Code Playgroud)
在子宏的末尾关闭应用程序:
ExcelApp.Quit
Set ExcelApp = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)
但是,如果在文件关闭之前发生错误,则不会关闭不可见文件和应用程序并继续在操作系统中停留,不仅会占用内存和资源,还会阻止对打开的文件执行任何操作 - 重命名,打开或编辑它.
我想知道是否有办法在发生错误时关闭文件和应用程序 - 在当前的宏中或创建一个单独的宏来检测不可见的应用程序,没有变量指向并关闭它.
在过程的顶部使用错误处理程序,如
Set ExcelApp = CreateObject("Excel.Application")
On Error Goto CLOSE_FILE_ON_ERROR
'With that line you tell VBA to jump to the closing part if an error happens
Run Code Online (Sandbox Code Playgroud)
并在关闭文件之前使用此goto标记.
CLOSE_FILE_ON_ERROR:
ExcelApp.Quit
End Sub
Run Code Online (Sandbox Code Playgroud)
注意:您不需要,Set ExcelApp = Nothing 因为Excel会自动执行此操作End Sub.
如果您需要显示错误消息或其他内容,那么您的代码必须像这样扩展:
ExcelApp.Quit 'This is needed to regularly quit if there is no error
Exit Sub 'Don't run into error handling if there was no exeption
CLOSE_FILE_ON_ERROR:
Application.StatusBar = "Error occured"
ExcelApp.Quit 'This is needed to quit after an exeption if there is an error
End Sub
Run Code Online (Sandbox Code Playgroud)