vbnet
' ============================================================
' 复制文件夹内容到另一个文件夹
' srcPath : 源文件夹路径(必须存在)
' dstPath : 目标文件夹路径(不存在则自动创建)
' overwrite: True = 覆盖同名文件; False = 跳过已存在文件
' 返回值 : True = 成功; False = 失败
' ============================================================
Function CopyFolderContents(ByVal srcPath As String, _
ByVal dstPath As String, _
ByVal overwrite As Boolean) As Boolean
Dim fso As Object
Dim srcFolder As Object
Dim subFolder As Object
Dim fileItem As Object
Dim targetPath As String
Set fso = CreateObject("Scripting.FileSystemObject")
' ---------- 1. 检查源文件夹是否存在 ----------
If Not fso.FolderExists(srcPath) Then
MsgBox "源文件夹不存在:" & vbCrLf & srcPath, vbExclamation, "错误"
CopyFolderContents = False
Exit Function
End If
' ---------- 2. 目标文件夹不存在则创建 ----------
If Not fso.FolderExists(dstPath) Then
On Error GoTo CreateErr
fso.CreateFolder dstPath
On Error GoTo 0
End If
Set srcFolder = fso.GetFolder(srcPath)
' ---------- 3. 复制文件 ----------
For Each fileItem In srcFolder.Files
targetPath = fso.BuildPath(dstPath, fileItem.Name)
If fso.FileExists(targetPath) Then
' 文件已存在
If overwrite Then
On Error GoTo CopyErr
fso.CopyFile fileItem.Path, targetPath, True ' 覆盖
On Error GoTo 0
End If
' overwrite = False 时直接跳过
Else
' 文件不存在,直接复制
On Error GoTo CopyErr
fso.CopyFile fileItem.Path, targetPath, False
On Error GoTo 0
End If
Next fileItem
' ---------- 4. 递归复制子文件夹 ----------
For Each subFolder In srcFolder.SubFolders
targetPath = fso.BuildPath(dstPath, subFolder.Name)
If Not CopyFolderContents(subFolder.Path, targetPath, overwrite) Then
CopyFolderContents = False
Exit Function
End If
Next subFolder
CopyFolderContents = True
Exit Function
CreateErr:
MsgBox "无法创建目标文件夹:" & vbCrLf & dstPath & vbCrLf & Err.Description, vbCritical, "错误"
CopyFolderContents = False
Exit Function
CopyErr:
MsgBox "复制文件失败:" & vbCrLf & fileItem.Path & vbCrLf & Err.Description, vbCritical, "错误"
CopyFolderContents = False
Exit Function
End Function
-
✅ 复制前检查源文件夹是否存在
-
✅ 目标文件夹不存在则自动创建
-
✅ 通过参数控制是否覆盖已存在的文件
-
✅ 支持递归复制子文件夹