How to do a “Save As” in vba code, saving my current Excel workbook with datestamp?

前端 未结 7 1433
旧时难觅i
旧时难觅i 2020-12-03 07:35

I have an Excel Workbook that on form button click I want to save a copy of the workbook with the filename being the current date.

I keep trying the the following

7条回答
  •  失恋的感觉
    2020-12-03 08:20

    Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

    Stop recording and you can start inspecting your code.

    I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

    Option Explicit
    
    Sub SaveFile()
    
    Dim fdate As Date
    Dim fname As String
    Dim path As String
    
    fdate = Range("A1").Value
    path = Application.ActiveWorkbook.path
    
    If fdate > 0 Then
        fname = "Event " & fdate
        Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
            FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    Else
        MsgBox "Chose a date for the event", vbOKOnly
    End If
    
    End Sub
    

    Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

提交回复
热议问题