none
Copy latest file from one folder to another RRS feed

  • Question

  • Hi

    Having a folder ”C:\A\” containing lots of files.

    Want to copy the newest/latest file in “C:\A\” to another folder “C:\B\”

    If possible, I want to use the “Date Modified” as criteria.

    Is it possible, and if its is, how do I do it?



    Cheers // Peter Forss Stockholm

    Thursday, November 7, 2019 10:05 AM

Answers

  • The following should do it

    Sub LatestFileInFolder()
    Dim FSO As Object
    Dim oFolder As Object
    Dim oFile As Object
    Dim dDate As Date
    Dim strName As String
    Const strPath As String = "C:\A"
    Const startDate As Date = "01/01/1900"
        Set FSO = CreateObject("Scripting.FileSystemObject")
        Set oFolder = FSO.GetFolder(strPath)
        dDate = startDate
        For Each oFile In oFolder.Files
            If oFile.datelastmodified > dDate Then
                strName = oFile.Name
                dDate = oFile.datelastmodified
            End If
        Next oFile
        FSO.CopyFile strPath & "\" & strName, "C:\B\"
    lbl_Exit:
        Set FSO = Nothing
        Set oFile = Nothing
        Set oFolder = Nothing
        Exit Sub
    End Sub


    Graham Mayor - Word MVP
    www.gmayor.com

    • Marked as answer by ForssPeterNova Thursday, November 7, 2019 5:06 PM
    Thursday, November 7, 2019 11:59 AM

All replies

  • The following should do it

    Sub LatestFileInFolder()
    Dim FSO As Object
    Dim oFolder As Object
    Dim oFile As Object
    Dim dDate As Date
    Dim strName As String
    Const strPath As String = "C:\A"
    Const startDate As Date = "01/01/1900"
        Set FSO = CreateObject("Scripting.FileSystemObject")
        Set oFolder = FSO.GetFolder(strPath)
        dDate = startDate
        For Each oFile In oFolder.Files
            If oFile.datelastmodified > dDate Then
                strName = oFile.Name
                dDate = oFile.datelastmodified
            End If
        Next oFile
        FSO.CopyFile strPath & "\" & strName, "C:\B\"
    lbl_Exit:
        Set FSO = Nothing
        Set oFile = Nothing
        Set oFolder = Nothing
        Exit Sub
    End Sub


    Graham Mayor - Word MVP
    www.gmayor.com

    • Marked as answer by ForssPeterNova Thursday, November 7, 2019 5:06 PM
    Thursday, November 7, 2019 11:59 AM
  • Graham

    Thank you very much!

    Worked nice and smooth :-)


    Cheers // Peter Forss Stockholm

    Thursday, November 7, 2019 5:07 PM