Wednesday, January 3, 2018

Overwrite an Existing File Using VBA Code in Excel

This tutorial will help you in, allowing your Macro/VBA code to overwrite an existing Excel file.

This will allows you to do things like:

Export a weekly report to a specific file and overwrite that file each week.

Note: The technique in this tutorial does not require any confirmation in order to overwrite the file.

Overwrite A File Using VBA

Add these two lines to any macro to allow them to overwrite a file without having the confirmation window appear:



Add to the top of the macro:
 Application.DisplayAlerts = False  

Add to the bottom of the macro:
 Application.DisplayAlerts = True  

Application.DisplayAlerts controls if Excel will show pop-up window alert messages, such as when you go to overwrite an existing file and Excel wants to warn you about that.

When you set this value to False, these messages will not appear and, so, you won't have to confirm anything that the macro does.

Make sure to set it back to True at the end of the macro so that Excel will function normally again after the macro has finished running.

Example

Here is a simple macro that you can use to test this out:
 Sub Save_File_Overwrite()  
   
 'Save the current workbook as Test.xlsm  
 ThisWorkbook.SaveAs "C:\Test.xlsm"  
   
 End Sub  

Run the above macro twice from a macro-enabled workbook. The second time that you run it, you will see a confirmation dialogue box asking if you want to overwrite the existing file or not.

Add the DisplayAlerts lines of code to the file and try it again:
 Sub Save_File_Overwrite()  
   
 'Don't show confirmation window  
 Application.DisplayAlerts = False  
   
 'Save the current workbook as Test.xlsm  
 ThisWorkbook.SaveAs "C:\Directory\Test.xlsm"  
   
 'Allow confirmation windows to appear as normal  
 Application.DisplayAlerts = True  
   
 End Sub  

Now, the file will overwrite the existing file without making a mention of it.

Note:

Be careful! When you disable alerts in Excel, data can be overwritten without you knowing about it. If you have a large and complex macro that works fine except for one area where you want to save the file, disable alerts only for that one area and enable them afterwards for the rest of the macro; this reduces the chance that other data will get overwritten without warning.

No comments:

Post a Comment