How To Delete Opened Excel file with VBA

Do you want to restrict user not to use the file after a specific date? You can easily do that in VBA. You can delete the file when they open it after a specific date.

How to delete opened file?

To Delete a file from hard drive, the file has to be either closed or read-only. Here is a code that can do the trick when the file is opened in exclusive mode. This code will check the current date and if it is greater than the date specified it will check the file access to read only. And when the file is read-only, We can just use Kill command to delete any file.

Private Sub Workbook_Open()
      If date > #15/10/2018# then
            ThisWorkbook.ChangeFileAccess xlReadOnly
            Kill ThisWorkbook.FullName
            ThisWorkbook.Close 0
      Endif

End Sub

How it works?

You need to write this code in Workbook code window. This is actually a workbook open event which will auto run when user open the workbook. As soon as it check the date is later than the sepcified, it will make file read only and delete it and then close it. And now, there wont be a file availabel to re-open.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *