Adding error code to Excel macro

How do I put error code in this macro.  If the file already exsists and I select "NO" do not overright I get an error where to macro should just terminate.

Sub SaveQuit()
      Dim Response As Integer
      ThisFile = Range("k19").Value
      ActiveWorkbook.SaveAs Filename:=ThisFile, FileFormat:=52
      ' Displays a message box with the yes and no options.
            Response = MsgBox(prompt:="Quit Program?", Buttons:=vbYesNo)
      ' If statement to check if the yes button was selected.
      If Response = vbYes Then
         Application.Quit
      Else
         ' The no button was selected.
         End If
   End Sub
mweidnerAsked:
Who is Participating?
 
Wayne Taylor (webtubbs)Commented:
Hi mweidner,

Try something like this....

Sub SaveQuit()
    Dim thisfile As String: thisfile = Range("k19").Value
    If Dir(thisfile) <> "" Then
        'file exists
        ActiveWorkbook.SaveAs Filename:=thisfile, FileFormat:=52
        ' Displays a message box with the yes and no options.
        If MsgBox(prompt:="Quit Program?", Buttons:=vbYesNo) = vbYes Then
        'Yes selected
            Application.Quit
        Else
            ' The no button was selected.
           
        End If
    Else
        'file does not exist
       
    End If
End Sub

Regards,

Wayne
0
 
jindalankushCommented:
try it
 If Dir(ThisFile) <> "" Then Kill (ThisFile) then
   If MsgBox(prompt:="Quit Program?", Buttons:=vbYesNo) = vbYes Then
         Application.Quit
  else
    ActiveWorkbook.SaveAs Filename:=ThisFile, FileFormat:=52
 end if
end if
0
 
jindalankushCommented:
sorry on last thread try it
 If Dir(ThisFile) <> "" Then then
   If MsgBox(prompt:="Quit Program?", Buttons:=vbYesNo) = vbYes Then
         Application.Quit
  else
       Kill (ThisFile)
    ActiveWorkbook.SaveAs Filename:=ThisFile, FileFormat:=52
 end if
end if
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.