Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Move files with certain prefix to another folder

0

Hi experts,

I  have  a problem  about  move  files  from  folder  to  another  based certain prefix 

the  code   doesn't  work  for  me,  but  when  I  create  folder  to  become  into  source folder "C:\Users\PC-AL\Downloads\DATA\"   then  the  code  moves  the  files  from  folder  to  another  .  why  this  case  does  for  me ?

Sub MoveFiles()
    Dim DestinationFolder   As String
    Dim FileExtention       As String
    Dim SourceFile          As String
    Dim SourceFolder        As String
    On Error Resume Next
    SourceFolder = "C:\Users\PC-AL\Downloads\"                                                  
    DestinationFolder = "C:\Users\PC-AL\Downloads\rr\"                                        
    FileExtention = "pdf"                                                      
    If Dir(DestinationFolder, vbDirectory) = 0 Then MkDir DestinationFolder     
    SourceFile = Dir(SourceFolder & "*." & FileExtention)                        
    Do While SourceFile Like "PR*"              
        Name (SourceFolder & SourceFile) As (DestinationFolder & SourceFile)     
        SourceFile = Dir                                                        
    Loop
End Sub
Answer
Discuss

Answers

0
Selected Answer

Ali

Your Do While loop doesn't work for me (when I change SourceFolder and DestinationFolder to suit my PC) but I've changed that and added an If test which seems to work well (note the * wildcard isn't used), changes in bold including spelling of "extension"):

Sub MoveFiles()
    Dim DestinationFolder   As String
    Dim FileExtension       As String
    Dim SourceFile          As String
    Dim SourceFolder        As String
    On Error Resume Next

    SourceFolder = "C:\Users\PC-AL\Downloads\"
    DestinationFolder = "C:\Users\PC-AL\Downloads\rr\"
    FileExtension = "pdf"
    If Dir(DestinationFolder, vbDirectory) = 0 Then MkDir DestinationFolder
    SourceFile = Dir(SourceFolder & "*." & FileExtension)

    'Loop though files
    Do While Len(SourceFile) > 0
    ' check filename against desired start string
        If InStr(SourceFile, "PR") = 1 Then
            Name (SourceFolder & SourceFile) As (DestinationFolder & SourceFile)
        End If
        SourceFile = Dir
    Loop
End Sub

Hope this works for you (and only moves files like PR*.pdf)

Discuss

Discussion

Hi John ! 
great  !  it  works 
thanks  for  your  help .
Ali M (rep: 28) Apr 17, '22 at 5:07 pm
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login