Search code examples
excelvbadirectoryfilesystemsmove

Moving folders to another directory


I recently posted a question here about moving files to another directory (Moving files to another directory), now I want to move folders, which will then be archived.

The layout is the same with the existing folder in A, target in B and a column C to confirm if completed.

image example

Code provided was

Sub move_files()
    Dim i As Long
    With ActiveSheet
        For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
            Err.Clear
            On Error Resume Next
            Name (.Cells(i, 1)) As .Cells(i, 2) & "\" & StrReverse(Split(StrReverse(.Cells(i, 1)), "\")(0))
            If Err = 0 Then .Cells(i, 3) = "YES" Else .Cells(i, 3) = "NO"
            On Error GoTo 0
        Next
    End With
End Sub

Given I am trying to move an entire column, does anyone know if the above can be adapted to move the folder as it only currently works for files. I have searched online but is usually only for one file.


Solution

  • This is a revised version moving folders only. Hopefully it will work.

    Sub move_folders()
      Dim i As Long
      Dim oFSO As Object
      Dim sep As String
    
      Set oFSO = CreateObject("Scripting.FileSystemObject")
      With ActiveSheet
        For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
          Err.Clear
          If Left(StrReverse(.Cells(i, 2)), 1) = "\" Then sep = "" Else sep = "\"
          On Error Resume Next
          oFSO.MoveFolder .Cells(i, 1), .Cells(i, 2) & sep & StrReverse(Split(StrReverse(.Cells(i, 1)), "\")(0))
          If Err = 0 Then .Cells(i, 3) = "YES" Else .Cells(i, 3) = "NO"
          On Error GoTo 0
        Next
      End With
    End Sub