I am trying to copy files between folders using VBA in excel,using filesystemobject.CopyFolder but only on C: drive, but can't do it across network drives
I have tried using this procedure
Sub aatest() 'Richards file copy procedure
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "\\swv082fs\Data\test"
ToPath = "C:\Users\rilindley\Data"
If Right(FromPath, 1) = "\" Then
FromPath = Left(FromPath, Len(FromPath) - 1)
End If
If Right(ToPath, 1) = "\" Then
ToPath = Left(ToPath, Len(ToPath) - 1)
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFolder Source:=FromPath, Destination:=ToPath
End Sub
I am trying to copy files between folders using VBA in excel,using filesystemobject.CopyFolder but only on C: drive, but can't do it across network drives
I have tried using this procedure
Sub aatest() 'Richards file copy procedure
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "\\swv082fs\Data\test"
ToPath = "C:\Users\rilindley\Data"
If Right(FromPath, 1) = "\" Then
FromPath = Left(FromPath, Len(FromPath) - 1)
End If
If Right(ToPath, 1) = "\" Then
ToPath = Left(ToPath, Len(ToPath) - 1)
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFolder Source:=FromPath, Destination:=ToPath
End Sub
Your approach seems to be generally sound, I think you just need to add some error checking to your code. The issue you're encountering is likely related to network permissions or the way the network path is being accessed:
FromPath
and ToPath
.WScript.Shell
can bypass certain permission issues with network paths.Try using the WScript.Shell
approach, or handle errors more gracefully:
Sub CopyNetworkFolder()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "\\swv082fs\Data\test\"
ToPath = "C:\Users\rilindley\Data\"
On Error GoTo ErrorHandler
Set FSO = CreateObject("Scripting.FileSystemObject")
' Check if source folder exists
If Not FSO.FolderExists(FromPath) Then
MsgBox "Source folder doesn't exist: " & FromPath, vbExclamation
Exit Sub
End If
' Check if destination folder exists, create if it doesn't
If Not FSO.FolderExists(ToPath) Then
FSO.CreateFolder ToPath
End If
' Copy the folder
FSO.CopyFolder Source:=FromPath, Destination:=ToPath
MsgBox "Folder copied successfully!", vbInformation
Exit Sub
ErrorHandler:
MsgBox "Error: " & Err.Description, vbCritical
End Sub