Search code examples
vbaexcelexcel-2007

How to Add Date and Time To File Name Using VBA in Excel


Thanks to Siddharth Rout at this Post I learned how to save a sheet to a new Worksheet. Now my question is how I can add Date and Time of file creation like:

TestSheet_25May2013_5pm.xls

Sub SaveSheet()
    Dim FName As String

    ActiveSheet.Copy
    With ActiveSheet.UsedRange
        .Copy
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
    End With
    Application.CutCopyMode = False


    FName = "C:\Users\somebody\Documents\TestSheet" & Format(Range("E19"), "mmm-d-yyyy") & ".xlsm"
    ActiveWorkbook.SaveAs Filename:=FName, _
                          FileFormat:=xlOpenXMLWorkbookMacroEnabled



End Sub

can you please let me know how to do this?


Solution

  • Change

    FName = "C:\Users\somebody\Documents\TestSheet" & _
            Format(Range("E19"), "mmm-d-yyyy") & ".xlsm"
    

    to

    FName = "C:\Users\somebody\Documents\TestSheet_" & _
            Format(Date, "ddmmmyyyy") & ".xlsm"
    

    If you are picking the date from Range("E19") then ensure that the cell has a valid date.. In such a case the code becomes

    FName = "C:\Users\somebody\Documents\TestSheet_" & _
            Format(Range("E19"), "ddmmmyyyy") & ".xlsm"