Trying_hard
Trying_hard

Reputation: 9501

Closing Macro with current date

I am using a macro to close several files and one of them uses a current date in the file name. I need the macro to click in the workbook and then close it and save it. I think I almost have it but I just can'tget the macro to click in the active workbook, which filename will change daily. This is what I have.

Dim ClosePath As String
Dim ClosePathDate As String

ClosePath = "File_":
ClosePathDate = ClosePath & Format(Date, "YYYYMMDD") & ".xlsx"

Windows("ClosePathDate").Activate
Sheets("Sheet1").Select
Range("A1").Select
ActiveWorkbook.Close SaveChanges:=True

I am not sure how to use " Windows("ClosePathDate") " I also tried Windows=ClosePathDate.Activate, no luck.

Please help.

Upvotes: 2

Views: 550

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149277

This will work even if the workbook is open in another Excel Instance. BTW, you do not need to select it in order to close it.

Sub Sample()
    Dim ClosePath As String
    Dim ClosePathDate As String
    Dim xlObj As Object

    ClosePath = "File_":
    ClosePathDate = ClosePath & Format(Date, "YYYYMMDD") & ".xlsx"

    '~~> Replace "C:\" with the relevant path
    Set xlObj = GetObject("C:\" & ClosePathDate)
    xlObj.Application.Workbooks(ClosePathDate).Close SaveChanges:=False
End Sub

Another way

Sub Sample()
    Dim wb As Workbook
    Dim ClosePath As String
    Dim ClosePathDate As String

    ClosePath = "File_":
    ClosePathDate = ClosePath & Format(Date, "YYYYMMDD") & ".xlsx"

    Set wb = Workbooks(ClosePathDate)

    wb.Close SaveChanges:=False
End Sub

Upvotes: 2

Related Questions