简体   繁体   中英

Copy all files from one directory to another

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM