Ulquiorra Schiffer
Ulquiorra Schiffer

Reputation: 89

Close Excel file when error message pops up

So what this script does is check if file A is opened, if file A is not opened it should display the error message, if the error message displays I would like the Excel file to close.

For some reason, I can't get my head around it. I tried Application.Quit, but that just closes everything in Excel, I tried doing just the specific window Excel window for file A, but that seems like a complex problem.

I also tried Application.ActiveWindow.Close and SaveChanges:=False ActiveWorkbook.Close SaveChanges:=False which works best.

My question how to close the Excel after the error message pops up?

Sub PullData()

Dim WB As Workbook
On Error Resume Next
    Set WB = Workbooks("A.xlsx")
    If Err Then MsgBox "Text - Text.xlsx Text." & vbNewLine & "" & vbNewLine & "" & "Text Text.xlsx Text" & vbNewLine & "" & vbNewLine & "Text" & vbNewLine & "" & vbNewLine & "Text.xlsx Text"

Workbooks("A.xlsx").Worksheets("A").Range("A2:AD9999").Copy _
Workbooks("B.xlsm").Worksheets("B").Range("A2")
Worksheets("Text").Range("A1").AutoFilter Field:=1, Criteria1:="YES"
On Error GoTo 0

End Sub

Upvotes: 0

Views: 850

Answers (1)

norie
norie

Reputation: 9857

If you want to close the workbook the code is in when the workbook 'A.xlsx' is not open you can use this.

 If Err Then 
     MsgBox "A.xlsx not open!"
     ThisWorkbook.Close
 End If

Upvotes: 1

Related Questions