Copy Excel Files from a list into a new Folder

kalyan46

New Member
Joined
Mar 13, 2017
Messages
21
Office Version
  1. 365
Hello, I have this code that will take a list of Part Numbers (in column A) search a folder where they are located and copy them into another folder. However, it is not copying the exact list from column A. Example: PN listed in column A might be 12345, the code might bring back 12345-1 instead of the 12345 as listed. I need the exact reference list.
PLEASE HELP
smile.gif



Code:
Sub QIPProcess()
'You can use this to delete all xl? files in the folder Test
On Error Resume Next
Kill "\\us108fp00\data\Krshare\QIP conversions\PrintQIPTempFile\*.xl*"
On Error GoTo 0

'*************************************************************
'****** Change these 2 Const values to match with your
'****** worksheet layout for the list of filenames on it
'put the column letter that your list is in as this Const
Const listColumn = "A"
'put the first row that a file is listed in as this Const
Const firstFileRow = 2 ' assumes a label in row 1
'*************************************************************

Dim sourcePath As String
Dim destPath As String
Dim listOfSourceFiles As Range
Dim anySourceFile As Range
'dictionary object to get list of files in source folder initially
Dim allFiles As Object
'will be an array with contents of allFiles in it
'so we can reference them for use
Dim filesInFolder As Variant
Dim arrayElement As Variant

Dim lastRow As Long
Dim anyFileName As String
Dim copiedCount As Long

'check if there any files listed on the active sheet
lastRow = Range(listColumn & Rows.Count).End(xlUp).Row
If lastRow < firstFileRow Or _
IsEmpty(Range(listColumn & lastRow)) Then
MsgBox "There are no files listed to be copied on the active sheet.", _
vbOKOnly + vbExclamation, "No Files to Copy"
Exit Sub
End If

sourcePath = BrowseFolderDialog("Select the Folder with all files in it")
If sourcePath = vbNullString Then
MsgBox "No source folder selected. Quitting.", _
vbOKOnly + vbExclamation, "No Source Folder Chosen"
Exit Sub
Else
sourcePath = sourcePath & Application.PathSeparator
End If
destPath = BrowseFolderDialog("Now select the Folder to copy files into")
If destPath = vbNullString Then
MsgBox "No destination folder selected. Quitting.", _
vbOKOnly + vbExclamation, "No Destination Folder Chosen"
Exit Sub
Else
destPath = destPath & Application.PathSeparator
End If

'set reference to the list of files to be copied.
Set listOfSourceFiles = Range(listColumn & firstFileRow & ":" _
& listColumn & lastRow)
'build list of files in the source folder that can be
'searched very rapidly when we need to
Set allFiles = CreateObject("Scripting.dictionary")
anyFileName = Dir$(sourcePath & "*.*")
Do While anyFileName <> ""
DoEvents ' let system do background tasks
If Not allFiles.Exists(anyFileName) Then
allFiles.Add anyFileName, 1
End If
anyFileName = Dir$()
Loop

'extract file names into variant array
filesInFolder = allFiles.keys
'empty out the dictionary object just to recover memory
allFiles.RemoveAll

'work through the list of files to be copied
For Each anySourceFile In listOfSourceFiles
DoEvents ' let system do background tasks
'work through each filename in array filesInFolder
'make sure there is a filename to look for
If Not IsEmpty(anySourceFile) Then
For Each arrayElement In filesInFolder
'if the file in the source folder starts
'with the filename from the worksheet
'then copy that file to the destination folder
If InStr(arrayElement, anySourceFile) = 1 Then
FileCopy sourcePath & arrayElement, destPath & arrayElement
copiedCount = copiedCount + 1
'done here, no need to look for more matches
Exit For ' exit arrayElement loop
End If
Next ' end arrayElement loop
End If
Next ' end anySourceFile loop

'housekeeping cleanup: makes sure all RAM assigned released back to system
Erase filesInFolder
Set allFiles = Nothing
Set listOfSourceFiles = Nothing
'announce job done
MsgBox copiedCount & " Files were copied.", _
vbOKOnly + vbInformation, "Task Completed"
End Sub
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
kaylyan46,

Try replacing this line...
Code:
If InStr(arrayElement, anySourceFile) = 1 Then

with this line...
Code:
If arrayElement = anySourceFile.Value Then

The InStr function looks for the condition where anySourceFile is contained within arrayElement; ie, not an exact match.

Cheers,

tonyyy
 
Upvote 0
Hello.
when I run the updated line of code, it is still not bringing back the exact match.
I appreciate your assistance
 
Upvote 0
Single-step through the code and check the pertinent variables after each relevant step
 
Upvote 0
still having the same problem. not bringing back the exact match. so close, please help :)
I have added the entire code.

Code:
[CODE]Sub CopyFilesToAnotherFolder()
 '*************************************************************
 '****** Change these 2 Const values to match with your
 '****** worksheet layout for the list of filenames on it
   'put the column letter that your list is in as this Const
   Const listColumn = "A"
   'put the first row that a file is listed in as this Const
   Const firstFileRow = 2 ' assumes a label in row 1
 '*************************************************************

  Dim sourcePath As String
   Dim destPath As String
   Dim listOfSourceFiles As Range
   Dim anySourceFile As Range
   'dictionary object to get list of files in source folder initially
   Dim allFiles As Object
   'will be an array with contents of allFiles in it
   'so we can reference them for use
   Dim filesInFolder As Variant
   Dim arrayElement As Variant

  Dim lastRow As Long
   Dim anyFileName As String
   Dim copiedCount As Long
  'check if there any files listed on the active sheet
   lastRow = Range(listColumn & Rows.Count).End(xlUp).Row
   If lastRow < firstFileRow Or _
    IsEmpty(Range(listColumn & lastRow)) Then
     MsgBox "There are no files listed to be copied on the active sheet.", _
      vbOKOnly + vbExclamation, "No Files to Copy"
     Exit Sub
   End If
  sourcePath = BrowseFolderDialog("Select the Folder with all files in it")
   If sourcePath = vbNullString Then
     MsgBox "No source folder selected. Quitting.", _
      vbOKOnly + vbExclamation, "No Source Folder Chosen"
     Exit Sub
   Else
     sourcePath = sourcePath & Application.PathSeparator
   End If
   destPath = BrowseFolderDialog("Now select the Folder to copy files into")
   If destPath = vbNullString Then
     MsgBox "No destination folder selected. Quitting.", _
      vbOKOnly + vbExclamation, "No Destination Folder Chosen"
     Exit Sub
   Else
     destPath = destPath & Application.PathSeparator
   End If

  'set reference to the list of files to be copied.
   Set listOfSourceFiles = Range(listColumn & firstFileRow & ":" _
    & listColumn & lastRow)
   'build list of files in the source folder that can be
   'searched very rapidly when we need to
   Set allFiles = CreateObject("Scripting.dictionary")
   anyFileName = Dir$(sourcePath & "*.*")
   Do While anyFileName <> ""
     DoEvents ' let system do background tasks
     If Not allFiles.Exists(anyFileName) Then
       allFiles.Add anyFileName, 1
     End If
     anyFileName = Dir$()
   Loop

'extract file names into variant array
   filesInFolder = allFiles.keys
   'empty out the dictionary object just to recover memory
   allFiles.RemoveAll
  'work through the list of files to be copied
   For Each anySourceFile In listOfSourceFiles
     DoEvents ' let system do background tasks
     'work through each filename in array filesInFolder
     'make sure there is a filename to look for
     If Not IsEmpty(anySourceFile) Then
       For Each arrayElement In filesInFolder
         'if the file in the source folder starts
         'with the filename from the worksheet
         'then copy that file to the destination folder
         If arrayElement = anySourceFile.Value Then  'updated was If InStr(arrayElement, anySourceFile) = 1 Then
           FileCopy sourcePath & arrayElement, destPath & arrayElement
           copiedCount = copiedCount + 1
           'done here, no need to look for more matches
           Exit For ' exit arrayElement loop
         End If
       Next ' end arrayElement loop
     End If
   Next ' end anySourceFile loop
  'housekeeping cleanup: makes sure all RAM assigned released back to system
   Erase filesInFolder
   Set allFiles = Nothing
   Set listOfSourceFiles = Nothing
   'announce job done
   MsgBox copiedCount & " Files were copied.", _
    vbOKOnly + vbInformation, "Task Completed"
 End Sub


'BrowseFolderDialog source: [URL]http://www.cpearson.com/excel/browsefolder.aspx[/URL]
 Function BrowseFolderDialog(Title As String, _
         Optional InitialFolder As String = vbNullString, _
         Optional InitialView As Office.MsoFileDialogView = _
             msoFileDialogViewList) As String
     Dim V As Variant
     Dim InitFolder As String
     With Application.FileDialog(msoFileDialogFolderPicker)
         .Title = Title
         .InitialView = InitialView
         If Len(InitialFolder) > 0 Then
             If Dir(InitialFolder, vbDirectory) <> vbNullString Then
                 InitFolder = InitialFolder
                 If Right(InitFolder, 1) <> "" Then
                     InitFolder = InitFolder & ""
                 End If
                 .InitialFileName = InitFolder
             End If
         End If
         .Show
         On Error Resume Next
         Err.Clear
         V = .SelectedItems(1)
         If Err.Number <> 0 Then
             V = vbNullString
         End If
     End With
     BrowseFolderDialog = CStr(V)
 End Function
[/CODE]
 
Upvote 0
How many characters are in the sourcePath and destPath? And how many characters are in the shortest and longest file names?

sourcePath and destPath, declared as String variables, have a limit of 255 characters. There may also be a character limit to the FileCopy function.
 
Upvote 0
Try this, it removes the file extension from the filenames for the comparison.
Code:
If Split(arrayElement, ".")(0) = anySourceFile Then
    FileCopy sourcePath & arrayElement, destPath & arrayElement
    copiedCount = copiedCount + 1
    'done here, no need to look for more matches
    Exit For    ' exit arrayElement loop
End If
 
Upvote 0
How exactly did you try what I suggested?

If you had 12345 then it would only ever match 12345.
 
Upvote 0
I took the code you provided above and 'commented out my old code

If Split(arrayElement, ".")(0) = anySourceFile Then 'If arrayElement = anySourceFile.Value Then 'updated was If InStr(arrayElement, anySourceFile) = 1 Then
FileCopy sourcePath & arrayElement, destPath & arrayElement
copiedCount = copiedCount + 1
'done here, no need to look for more matches
Exit For ' exit arrayElement loop
End If
Next ' end arrayElement loop
End If
Next ' end anySourceFile loop

Code:
Sub CopyFilesToAnotherFolder()
 '*************************************************************
 '****** Change these 2 Const values to match with your
 '****** worksheet layout for the list of filenames on it
   'put the column letter that your list is in as this Const
   Const listColumn = "A"
   'put the first row that a file is listed in as this Const
   Const firstFileRow = 2 ' assumes a label in row 1
 '*************************************************************

  Dim sourcePath As String
   Dim destPath As String
   Dim listOfSourceFiles As Range
   Dim anySourceFile As Range
   'dictionary object to get list of files in source folder initially
   Dim allFiles As Object
   'will be an array with contents of allFiles in it
   'so we can reference them for use
   Dim filesInFolder As Variant
   Dim arrayElement As Variant
  Dim lastRow As Long
   Dim anyFileName As String
   Dim copiedCount As Long
  'check if there any files listed on the active sheet
   lastRow = Range(listColumn & Rows.Count).End(xlUp).Row
   If lastRow < firstFileRow Or _
    IsEmpty(Range(listColumn & lastRow)) Then
     MsgBox "There are no files listed to be copied on the active sheet.", _
      vbOKOnly + vbExclamation, "No Files to Copy"
     Exit Sub
   End If
  sourcePath = BrowseFolderDialog("Select the Folder with all files in it")
   If sourcePath = vbNullString Then
     MsgBox "No source folder selected. Quitting.", _
      vbOKOnly + vbExclamation, "No Source Folder Chosen"
     Exit Sub
   Else
     sourcePath = sourcePath & Application.PathSeparator
   End If
   destPath = BrowseFolderDialog("Now select the Folder to copy files into")
   If destPath = vbNullString Then
     MsgBox "No destination folder selected. Quitting.", _
      vbOKOnly + vbExclamation, "No Destination Folder Chosen"
     Exit Sub
   Else
     destPath = destPath & Application.PathSeparator
   End If
  'set reference to the list of files to be copied.
   Set listOfSourceFiles = Range(listColumn & firstFileRow & ":" _
    & listColumn & lastRow)
   'build list of files in the source folder that can be
   'searched very rapidly when we need to
   Set allFiles = CreateObject("Scripting.dictionary")
   anyFileName = Dir$(sourcePath & "*.*")
   Do While anyFileName <> ""
     DoEvents ' let system do background tasks
     If Not allFiles.Exists(anyFileName) Then
       allFiles.Add anyFileName, 1
     End If
     anyFileName = Dir$()
   Loop
'extract file names into variant array
   filesInFolder = allFiles.keys
   'empty out the dictionary object just to recover memory
   allFiles.RemoveAll
  'work through the list of files to be copied
   For Each anySourceFile In listOfSourceFiles
     DoEvents ' let system do background tasks
     'work through each filename in array filesInFolder
     'make sure there is a filename to look for
     If Not IsEmpty(anySourceFile) Then
       For Each arrayElement In filesInFolder
         'if the file in the source folder starts
         'with the filename from the worksheet
         'then copy that file to the destination folder
      If Split(arrayElement, ".")(0) = anySourceFile Then   'If arrayElement = anySourceFile.Value Then  'updated was If InStr(arrayElement, anySourceFile) = 1 Then
           FileCopy sourcePath & arrayElement, destPath & arrayElement
           copiedCount = copiedCount + 1
           'done here, no need to look for more matches
           Exit For ' exit arrayElement loop
         End If
       Next ' end arrayElement loop
     End If
   Next ' end anySourceFile loop
  'housekeeping cleanup: makes sure all RAM assigned released back to system
   Erase filesInFolder
   Set allFiles = Nothing
   Set listOfSourceFiles = Nothing
   'announce job done
   MsgBox copiedCount & " Files were copied.", _
    vbOKOnly + vbInformation, "Task Completed"
 End Sub

'BrowseFolderDialog source: [URL]http://www.cpearson.com/excel/browsefolder.aspx[/URL]
 Function BrowseFolderDialog(Title As String, _
         Optional InitialFolder As String = vbNullString, _
         Optional InitialView As Office.MsoFileDialogView = _
             msoFileDialogViewList) As String
     Dim V As Variant
     Dim InitFolder As String
     With Application.FileDialog(msoFileDialogFolderPicker)
         .Title = Title
         .InitialView = InitialView
         If Len(InitialFolder) > 0 Then
             If Dir(InitialFolder, vbDirectory) <> vbNullString Then
                 InitFolder = InitialFolder
                 If Right(InitFolder, 1) <> "" Then
                     InitFolder = InitFolder & ""
                 End If
                 .InitialFileName = InitFolder
             End If
         End If
         .Show
         On Error Resume Next
         Err.Clear
         V = .SelectedItems(1)
         If Err.Number <> 0 Then
             V = vbNullString
         End If
     End With
     BrowseFolderDialog = CStr(V)
 End Function
 
Upvote 0

Forum statistics

Threads
1,214,786
Messages
6,121,553
Members
449,038
Latest member
Guest1337

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top