将所有文件从一个目录复制到另一个目录
Copy all files from one directory to another
如果文件夹 2 为空,我想将所有文件从文件夹 1 复制到文件夹 2。
例如:file1.txt
、file2.pdf
等存在于 folder1
中,并且有两个文件夹:folder1
和 folder2
,以及 folder1
应该将所有文件发送到 folder2
如果它是空的。
这是我的代码:
Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile "C:\Users\abc\Desktop\from\", "C:\Users\abc\Desktop\to"
如有疑问,请阅读 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.
改变
fso.CopyFile "C:\Users\abc\Desktop\from\", "C:\Users\abc\Desktop\to"
到
fso.CopyFile "C:\Users\abc\Desktop\from\*.*", "C:\Users\abc\Desktop\to\"
代码会将所有内容从源文件夹复制到目标文件夹。
但是,由于您只想在目标文件夹为空时复制,因此您需要先检查一下:
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
如果目标也不能包含任何文件夹,您还需要检查子文件夹是否存在。
如果文件夹 2 为空,我想将所有文件从文件夹 1 复制到文件夹 2。
例如:file1.txt
、file2.pdf
等存在于 folder1
中,并且有两个文件夹:folder1
和 folder2
,以及 folder1
应该将所有文件发送到 folder2
如果它是空的。
这是我的代码:
Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile "C:\Users\abc\Desktop\from\", "C:\Users\abc\Desktop\to"
如有疑问,请阅读 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.
改变
fso.CopyFile "C:\Users\abc\Desktop\from\", "C:\Users\abc\Desktop\to"
到
fso.CopyFile "C:\Users\abc\Desktop\from\*.*", "C:\Users\abc\Desktop\to\"
代码会将所有内容从源文件夹复制到目标文件夹。
但是,由于您只想在目标文件夹为空时复制,因此您需要先检查一下:
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
如果目标也不能包含任何文件夹,您还需要检查子文件夹是否存在。