One possible approach is to wrap the Excel handling in a custom class:
Class Excel
Private xl
Private Sub Class_Initialize
Set xl = CreateObject("Excel.Application")
End Sub
Private Sub Class_Terminate
For Each wb In xl.Workbooks
wb.Saved = True 'discard unsaved changes
wb.Close 'close workbook
Next
xl.Quit 'quit Excel
End Sub
Public Function OpenWorkbook(filename)
Set OpenWorkbook = xl.Workbooks.Open(filename)
End Function
Public Function NewWorkbook
Set NewWorkbook = xl.Workbooks.Add
End Function
Public Property Get Workbooks
Set Workbooks = xl.Workbooks
End Property
End Class
The procedure Class_Terminate
is automatically called whenever a class instance is destroyed. That way you can automatically close the open workbooks and quit Excel.
The class can be used like this:
Set xl = New Excel
Set wb = xl.OpenWorkbook("C:pathoyour.xlsx")
...
wb.Close
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…