+ Reply to Thread
Results 1 to 7 of 7

VBA Copying files from one location to another

Hybrid View

  1. #1
    Registered User
    Join Date
    05-21-2015
    Location
    England
    MS-Off Ver
    2013
    Posts
    25

    VBA Copying files from one location to another

    Afternoon all,

    I am using the below code (along with some formulas and a UDF) to transfer the latest file in a directory to another location.

    The UDF & Formulas compare the latest filename that was uploaded to the latest file in the source location, the names could be something like this:

    Last Upload - Upload_Data123.csv
    Latest file in source location: Upload_Data124.csv

    So the macro will transfer Upload_Data124.csv into the desired folder.

    However, sometimes the situation could be this:

    Last Upload - Upload_Data123.csv
    Latest file in source location: Upload_Data125.csv

    I need the code to copy all files GREATER than the last upload file across, so it would copy
    Upload_Data124.csv & Upload_Data125.csv

    Here is the code, any help would be appreciated:


    Sub Move_Files()
    
    Dim OutLookApp As Object
    Dim OutLookMailItem As Object
    Dim lastRow As Long
    Dim MailDest As String
    Dim subj As String
    Dim FSO As Object
    Dim SourceFileName, DestinFileName As String
    Set FSO = CreateObject("Scripting.Filesystemobject")
    
    
    Sheets("Insurer List").Select
       Range("A1").Select
       
    lastRow = ThisWorkbook.Worksheets("Insurer List").Cells(Rows.Count, "A").End(xlUp).Row
    
    For b = 2 To lastRow
    
        SourceFileName = Cells(b, 2).Value & Cells(b, 8).Value
        DestinFileName = Cells(b, 3).Value & Cells(b, 8).Value
        FSO.CopyFile source:=SourceFileName, Destination:=DestinFileName
        On Error Resume Next
        Next
    
    Msg "Files Moved Successfully"
    
    End Sub
    Thanks
    Dan

  2. #2
    Valued Forum Contributor
    Join Date
    03-16-2017
    Location
    UK
    MS-Off Ver
    2016
    Posts
    371

    Re: VBA Copying files from one location to another

    Hi Dan,

    That code seems to just copy every path that is in the Insurer List. I can't see any comparison between file names.

    Can you check this is the right code and attach a sample workbook?

  3. #3
    Registered User
    Join Date
    05-21-2015
    Location
    England
    MS-Off Ver
    2013
    Posts
    25
    I have protected the data so i have had to remove some of the formulas but i assure you it searches for a specific file.

    Attached is the example workbook
    Attached Files Attached Files

  4. #4
    Registered User
    Join Date
    05-21-2015
    Location
    England
    MS-Off Ver
    2013
    Posts
    25

    Re: VBA Copying files from one location to another

    Still struggling with this, so just a friendly bump if anyone has any thoughts?

  5. #5
    Valued Forum Contributor
    Join Date
    03-16-2017
    Location
    UK
    MS-Off Ver
    2016
    Posts
    371

    Re: VBA Copying files from one location to another

    Hi Dan,

    Since your bump I have been working on this in little bits of spare time I can find during the day. Hang in there

  6. #6
    Valued Forum Contributor
    Join Date
    03-16-2017
    Location
    UK
    MS-Off Ver
    2016
    Posts
    371

    Re: VBA Copying files from one location to another

    Hi Dan,

    I finished this off today on my lunch break. Lots of fun

    Due to the different styles of file counters you'll need to add a few columns to your table which tells the code where to look for the counter (and if it is a date).
    Additionally, the code ignores your "Transfer Required?" column since the formula used was unreliable, and by finding the difference between the file name counters we can infer whether a transfer is required or not.

    The code works with all the file name styles in your sample workbook and works if there are gaps in the incrementation, e.g. if Data123.csv is the last import and Data130.csv is the latest source file, but only Data123.csv, Data125.csv, Data129.csv, and Data130.csv exist, it will import those files that exist and skip the gaps. This is more likely to happen with the date counters of course.
    The code will print the transfer details to the console for information purposes. Example:
    Row 2         AutoWindscreenCoverOutput_({#})
    Row 3         BUD_{#}_EndOfFile
                  Src:= C:\TEST\SRC\Insurer 2\BUD_0006_EndOfFile.txt
                  Dst:= C:\TEST\DST\Insurer 2\20170724_150647_IMPORTED_BUD_0006_EndOfFile.txt
                                ** Transfer Successful **
                  Src:= C:\TEST\SRC\Insurer 2\BUD_0007_EndOfFile.txt
                  Dst:= C:\TEST\DST\Insurer 2\20170724_150647_IMPORTED_BUD_0007_EndOfFile.txt
                                ** Transfer Successful **
                  Src:= C:\TEST\SRC\Insurer 2\BUD_0008_EndOfFile.txt
                  Dst:= C:\TEST\DST\Insurer 2\20170724_150647_IMPORTED_BUD_0008_EndOfFile.txt
                                ** Transfer Successful **
    Row 4         AGX_N103FULL{#}
                  Src:= C:\TEST\SRC\Insurer 3\AGX_N103FULL0000002406.txt
                  Dst:= C:\TEST\DST\Insurer 3\20170724_150647_IMPORTED_AGX_N103FULL0000002406.txt
                                ** Transfer Successful **
    Row 5         BUDGExtract_{#}
                  Src:= C:\TEST\SRC\Insurer 4\BUDGExtract_000775.TXT
                  Dst:= C:\TEST\DST\Insurer 4\20170724_150647_IMPORTED_BUDGExtract_000775.TXT
                                ** Transfer Successful **
    Row 6         Windscreen_{#}_150341
                  Src:= C:\TEST\SRC\Insurer 5\Windscreen_03_07_2017_150341.txt
                  Dst:= C:\TEST\DST\Insurer 5\20170724_150647_IMPORTED_Windscreen_03_07_2017_150341.txt
                                ** Transfer Successful **
                  Src:= C:\TEST\SRC\Insurer 5\Windscreen_04_07_2017_150341.txt
                  Dst:= C:\TEST\DST\Insurer 5\20170724_150647_IMPORTED_Windscreen_04_07_2017_150341.txt
                                ** Transfer Successful **
                  Src:= C:\TEST\SRC\Insurer 5\Windscreen_05_07_2017_150341.txt
                  Dst:= C:\TEST\DST\Insurer 5\20170724_150647_IMPORTED_Windscreen_05_07_2017_150341.txt
                                ** Transfer Successful **
                  Src:= C:\TEST\SRC\Insurer 5\Windscreen_06_07_2017_150341.txt
                  Dst:= C:\TEST\DST\Insurer 5\20170724_150647_IMPORTED_Windscreen_06_07_2017_150341.txt
                                ** Transfer Successful **
    Row 7         IF_OGI_AW_EXCESS_{#}
    Row 8         LIS_OGI_AW_EXCESS_{#}
                  Src:= C:\TEST\SRC\Insurer 7\LIS_OGI_AW_EXCESS_07072017.txt
                  Dst:= C:\TEST\DST\Insurer 7\20170724_150647_IMPORTED_LIS_OGI_AW_EXCESS_07072017.txt
                                ** Transfer Successful **
    Row 9         IF_STR_AW_EXCESS_{#}
    Row 10        {#}_MKS
    Row 11        {#}Auto_Wind_policy_extract
    Row 12        MSWH{#}
                  Src:= C:\TEST\SRC\Insurer 11\MSWH002192
                  Dst:= C:\TEST\DST\Insurer 11\20170724_150647_IMPORTED_MSWH002192
                                ** Transfer Successful **
    Row 13        SD_OGI_AW_EXCESS_{#}
                  Src:= C:\TEST\SRC\Insurer 12\SD_OGI_AW_EXCESS_01072017.txt
                  Dst:= C:\TEST\DST\Insurer 12\20170724_150647_IMPORTED_SD_OGI_AW_EXCESS_01072017.txt
                                ** Transfer Successful **
                  Src:= C:\TEST\SRC\Insurer 12\SD_OGI_AW_EXCESS_05072017.txt
                  Dst:= C:\TEST\DST\Insurer 12\20170724_150647_IMPORTED_SD_OGI_AW_EXCESS_05072017.txt
                                ** Transfer Successful **
                  Src:= C:\TEST\SRC\Insurer 12\SD_OGI_AW_EXCESS_07072017.txt
                  Dst:= C:\TEST\DST\Insurer 12\20170724_150647_IMPORTED_SD_OGI_AW_EXCESS_07072017.txt
                                ** Transfer Successful **
    Row 14        {#}_ZEN

    Find my code below. You will need the functions after the main sub, too. Also included at the end are the subs I used to create files / folders to test the code (NB that I set all file extensions to .txt for testing purposes).

    Option Explicit
    
    Sub Move_Files_New()
        
        Dim oFSO As Object 'FileSystemObject to perform file copies
        Dim oREX As Object 'RegularExpressions to match strings with wildcards
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        Set oREX = CreateObject("VBScript.RegExp")
        
        Dim r As Long, lstR As Long      'row counters
        Dim i As Long, j As Long         'iteration counters
        Dim d As Integer, f As Integer   'variables to find counter in string
        Dim IsDate As Boolean            'store YES/NO column as boolean
        
        Dim sSN As String, sLN As String 'file name [Source, Last import]
        Dim sSE As String, sLE As String 'file extension [Source, Last import]
        Dim sSP As String, sDP As String 'file path (full) [Source, Destination]
        Dim sSC As String, sLC As String 'file counter [Source, Last import]
        Dim sSD As String, sLD As String 'file counter date [Source, Last import]
        Dim v As Variant, sFmt As String 'for manipulating date counter
        Dim dSD As Date, dLD As Date     'file counter as date value [Source, Last import]
        Dim lX  As Long                  'file counter difference
        Dim t1 As String, t2 As String, t3 As String 'for building file strings
        
        Const cSrcLoc As Long = 2        'Column number: VRN Source Location
        Const cImpLoc As Long = 3        'Column number: VRN Import Location
        Const cLst_FN As Long = 7        'Column number: Last Import File Name
        Const cSrc_FN As Long = 8        'Column number: Latest File (Source)
        Const cCtrDig As Long = 10       'Column number: Counter Digits Wide
        Const cCtrOff As Long = 11       'Column number: Counter Offset (from end)
        Const cCtrDat As Long = 12       'Column number: Counter Is Date?
        
        Const cPfixTS As Boolean = True  'prefix a timestamp to imported files?
        
        Dim ws As Worksheet
        Set ws = ThisWorkbook.Sheets("Insurer List")
        
        'show the worksheet and reset the cursor
        ws.Activate
        ws.[A1].Select
        
        'find last row
        lstR = ws.Cells(Rows.Count, cSrcLoc).End(xlUp).Row
        
        'iterate through the rows
        For r = 2 To lstR
            'set file names
            sSN = ws.Cells(r, cSrc_FN).Value
            sLN = ws.Cells(r, cLst_FN).Value
            'set extensions
            If InStrRev(sSN, ".") Then sSE = Mid(sSN, InStrRev(sSN, ".")) Else sSE = ""
            If InStrRev(sLN, ".") Then sLE = Mid(sLN, InStrRev(sLN, ".")) Else sLE = ""
            'remove ext from file names
            sSN = Mid(sSN, 1, Len(sSN) - Len(sSE))
            sLN = Mid(sLN, 1, Len(sLN) - Len(sLE))
            'varibles for counter
            d = Val(ws.Cells(r, cCtrDig)) 'digits wide
            f = Val(ws.Cells(r, cCtrOff)) 'offset (to left)
            'grab counters from file name
            sSC = Mid(sSN, Len(sSN) - (d - 1) - f, d)
            sLC = Mid(sLN, Len(sLN) - (d - 1) - f, d)
            'compare counters
            IsDate = IsTrue(ws.Cells(r, cCtrDat))
            If IsDate Then
                'we need to determine what format the date is in
                ' only works for dates with month as the middle section
                ' i.e. will not work for US dates with day in the middle
                oREX.Global = True 'all matches
                oREX.Pattern = "[^a-zA-Z0-9]" 'non-alphanumeric
                If oREX.Test(sSC) Then 'a good, delimited date
                    'check the first delimiter position to determine order
                    Set v = oREX.Execute(sSC)
                    If InStr(1, sSC, CStr(v(0))) = 3 Then
                        sFmt = JoinStr(CStr(v(0)), "DD", "MM", "YYYY")
                    Else
                        sFmt = JoinStr(CStr(v(0)), "YYYY", "MM", "DD")
                    End If
                    'replace source delimiter with VBA-recognised delimiter
                    ' and then set the date
                    dSD = DateValue(oREX.Replace(sSC, "/"))
                    dLD = DateValue(oREX.Replace(sLC, "/"))
                ElseIf Val(Mid(sSC, 3, 2)) > 12 Then 'very simple test that doesn't work for years 2000 - 2012
                    sFmt = "YYYYMMDD"
                    dSD = DateValue(JoinStr("/", Mid(sSC, 1, 4), Mid(sSC, 5, 2), Mid(sSC, 7, 2)))
                    dLD = DateValue(JoinStr("/", Mid(sLC, 1, 4), Mid(sLC, 5, 2), Mid(sLC, 7, 2)))
                Else
                    sFmt = "DDMMYYYY"
                    dSD = DateValue(JoinStr("/", Mid(sSC, 1, 2), Mid(sSC, 3, 2), Mid(sSC, 5, 4)))
                    dLD = DateValue(JoinStr("/", Mid(sLC, 1, 2), Mid(sLC, 3, 2), Mid(sLC, 5, 4)))
                End If
                lX = dSD - dLD
            Else
                lX = Val(sSC) - Val(sLC)
            End If
            'get source file name without counter
            t1 = Left(sSN, InStr(1, sSN, sSC) - 1)
            t2 = Mid(sSN, InStr(1, sSN, sSC) + Len(sSC))
            Debug.Print "Row"; r, t1 & "{#}" & t2
            If lX > 0 Then
                'import all the files
                For j = 1 To lX
                    'create new filename with counter
                    If IsDate Then
                        t3 = t1 & Format(dLD + j, sFmt) & t2
                    Else
                        t3 = t1 & Format(Val(sLC) + j, String(Len(sLC), "0")) & t2
                    End If
                    'set paths
                    sSP = ws.Cells(r, cSrcLoc).Value & t3 & sSE
                    sDP = ws.Cells(r, cImpLoc).Value & IIf(cPfixTS, TimeStamp, "") & t3 & sSE
                    'check source and destination files
                    If oFSO.FileExists(sSP) And Not oFSO.FileExists(sDP) Then
                        Debug.Print , "Src:= " & sSP
                        Debug.Print , "Dst:= " & sDP
                        'perform copy
                        oFSO.CopyFile Source:=sSP, Destination:=sDP
                        'add to xfer counter
                        i = i + 1
                        Debug.Print , , "** Transfer Successful **"
                    End If
                Next j
            ElseIf lX < 0 Then
                MsgBox "Something went wrong. Counter difference is " & lX & " for row " & r, vbCritical
                Debug.Print , "Error: Counter difference is " & lX
            End If
        Next r
        
        MsgBox i & " file(s) imported successfully."
        
        Set oFSO = Nothing
        Set oREX = Nothing
    
    End Sub
    
    Function IsTrue(TargetCells As Range) As Boolean
        
        Dim b() As Variant
        Dim r   As Range
        Dim c   As Long
        
        If TargetCells.Count <= 0 Then Exit Function
        ReDim b(1 To TargetCells.Count)
        For Each r In TargetCells
            c = c + 1
            b(c) = _
                r.Value <> 0 And _
                r.Value <> False And _
                r.Value <> "FALSE" And _
                r.Value <> "NO" And _
                r.Value <> ""
        Next r
        
        IsTrue = True
        
        For c = LBound(b) To UBound(b)
            If Not b(c) Then IsTrue = False: Exit For
        Next c
        
    End Function
    
    Function JoinStr(Delimiter As String, ParamArray Strings()) As String
        
        Dim itm As Variant
        
        For Each itm In Strings
            JoinStr = JoinStr & Delimiter & itm
        Next itm
        
        JoinStr = Mid(JoinStr, 2)
        
    End Function
    
    Function TimeStamp() As String
    
        TimeStamp = Format(Now, "YYYYMMDD_hhmmss") & "_IMPORTED_"
        
    End Function
    
    '***   Testing Code Below    ***
    '*** For Creating Test Files ***
    
    Sub TestDirs()
    
        On Error Resume Next
    
        Dim i As Integer
        
        MkDir "C:\TEST\"
        MkDir "C:\TEST\SRC"
        MkDir "C:\TEST\DST"
        
        For i = 1 To 13
            MkDir "C:\TEST\SRC\Insurer " & i
            MkDir "C:\TEST\DST\Insurer " & i
        Next i
        
    End Sub
    
    Sub InsertDirs()
        
        Dim r As Long
        
        For r = 2 To 14
            With ActiveSheet
                .Cells(r, 2).Value = "C:\TEST\SRC\Insurer " & r - 1 & "\"
                .Cells(r, 3).Value = "C:\TEST\DST\Insurer " & r - 1 & "\"
            End With
        Next r
        
    End Sub
    
    Sub CreateFiles()
        
        Dim oFSO As Object
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        
        Dim r As Long
        
        'All extensions changed to .txt for testing
        
        For r = 2 To 14
            With ActiveSheet
                oFSO.CreateTextFile .Cells(r, 2).Value & .Cells(r, 8).Value
                oFSO.CreateTextFile .Cells(r, 3).Value & .Cells(r, 6).Value
            End With
        Next r
        
    End Sub

    Also attached is the workbook that I used to create / test this.

    Enjoy!
    Attached Files Attached Files

  7. #7
    Valued Forum Contributor
    Join Date
    03-16-2017
    Location
    UK
    MS-Off Ver
    2016
    Posts
    371

    Re: VBA Copying files from one location to another

    Hi Dan,

    Have you tried this out? Did it work? Let me know
    If that takes care of your original question, please select Thread Tools from the menu link above to mark this thread as SOLVED.
    To say thanks to the user(s) who contributed towards the solution, you can use the "Add Reputation" button on their helpful post(s).
    Thanks!

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Copying Files : Userdefined Location to user defined destination folder
    By subbby in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 11-15-2016, 05:31 PM
  2. Copying files from one location to another based on list
    By maym in forum Excel Programming / VBA / Macros
    Replies: 11
    Last Post: 10-28-2016, 08:09 PM
  3. [SOLVED] Open excel files, copy sheet 1 to new location and close original files
    By ghostly1 in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 10-08-2015, 11:48 AM
  4. split text files stored in some location to multiple files based on a condition
    By GIRISH_KH in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 09-01-2013, 11:32 AM
  5. copying files from one location into another.
    By CWinkler in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 09-01-2011, 11:21 AM
  6. [SOLVED] Copying files from one location into another
    By CWinkler in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 09-01-2011, 11:20 AM
  7. Saving copying text files named in a column to a different location
    By twills in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 02-19-2010, 08:44 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1