Reputation: 41
I want to copy all file from folder1 to folder2 if folder 2 is empty.
For example: file1.txt
, file2.pdf
etc are present in folder1
, and there are two folders: folder1
and folder2
, and folder1
should send all files to folder2
if its empty.
Here's my code:
Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile "C:\Users\abc\Desktop\from\", "C:\Users\abc\Desktop\to"
Upvotes: 0
Views: 11206
Reputation: 200193
When in doubt, read the documentation:
object.CopyFile ( source, destination[, overwrite] )
Arguments
[...]
source
Required. Character string file specification, which can include wildcard characters, for one or more files to be copied.
destination
Required. Character string destination where the file or files from source are to be copied. Wildcard characters are not allowed.[...]
Remarks
Wildcard characters can only be used in the last path component of the source argument. For example, you can use:
[...]
If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching files. Otherwise, destination is assumed to be the name of a file to create.
Change
fso.CopyFile "C:\Users\abc\Desktop\from\", "C:\Users\abc\Desktop\to"
to
fso.CopyFile "C:\Users\abc\Desktop\from\*.*", "C:\Users\abc\Desktop\to\"
and the code will copy everything from the source folder to the destination folder.
However, since you only want to copy when the destination folder is empty, you'll want to check that first:
If fso.GetFolder("C:\Users\abc\Desktop\to").Files.Count = 0 Then
fso.CopyFile "C:\Users\abc\Desktop\from\*.*", "C:\Users\abc\Desktop\to\"
End If
If the destination must also not contain any folders you'll need to check for the existence of subfolders as well.
Upvotes: 2