Run VBA Code On Save

sathish2009

New Member
Joined
Nov 10, 2016
Messages
5
Hi,

My current macro code is

Code:
     Sub Autosave()     
     Dim Wkb As Workbook     Dim Wkbnew As Workbook
    Dim FilenamePath As String
    Set Wkb = ActiveWorkbook
    FilenamePath = Wkb.FullName
    Wkb.SaveAs ThisWorkbook.Path & ("\MyExcelData - " & Format(Now(), "DD-MMM-YYYY_ hh_mm AMPM") & ".xlsm")
    Kill FilenamePath
End Sub

And i would like to execute the vba code automatically on saving the file.

Thanks
 
Put this code into the code for ThisWorkbook (in your project window)


Code:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
     Dim Wkb As Workbook     Dim Wkbnew As Workbook
    Dim FilenamePath As String
    Set Wkb = ActiveWorkbook
    FilenamePath = Wkb.FullName
    Wkb.SaveAs ThisWorkbook.Path & ("\MyExcelData - " & Format(Now(), "DD-MMM-YYYY_ hh_mm AMPM") & ".xlsm")
    Kill FilenamePath
End Sub
 
Upvote 0
This is not for your module. It is for the workbook code. In your project window you will see your module. You will also see all your sheets above that and one called "This Workbook"

The code I mentioned should go into ThisWorkbook, not a new module or any existing one.



(Also looking at the above code, if you haven't done so already, please put those two Dim statements on separate lines. Its hard to tell on this message board if that is actually how it looks in your VBA or if it is just the HTML of this message board being cranky...)
 
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top