![](/img/trans.png)
[英]Excel VBA: Making a list of all files in a folder, including hyperlinks and copy data from each Excel file it finds
[英]Excel VBA copy folder, move all files - but if file exists skip
我正在嘗試使用 fso.folder 副本在網絡驅動器上創建備份數據庫。 我的意圖是移動文件夾中的所有文件,但如果備份驅動器上已存在文件,請跳過它,並復制文件夾中的其余文件。 我目前有
SourceFileName="C:\users\desktop\test1"
DestinFileName="C:\users\desktop\test2"
FSO.copyfolder Source:=Sourcefilename, Destination:=Destinfilename, OverwriteFiles:= False
但是,腳本在找到現有文件時出錯。 任何意見,將不勝感激。
folder part
應用On Error
。代碼
Option Explicit
Sub copyFilesNoOverwrite()
Const srcFolderPath As String = "C:\users\desktop\test1"
Const dstFolderPath As String = "C:\users\desktop\test2"
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(srcFolderPath) Then
MsgBox "Source Folder doesn't exist.", vbCritical, "No Source"
Exit Sub
End If
If .FolderExists(dstFolderPath) Then
Dim Sep As String: Sep = Application.PathSeparator
Dim fsoFile As Object
Dim FilePath As String
For Each fsoFile In .GetFolder(srcFolderPath).Files
FilePath = dstFolderPath & Sep & fsoFile.Name
If Not .FileExists(FilePath) Then
.CopyFile _
Source:=fsoFile.Path, _
Destination:=FilePath
End If
Next fsoFile
Else
.CopyFolder _
Source:=srcFolderPath, _
Destination:=dstFolderPath
End If
End With
End Sub
Sub copyFilesNoOverwriteOnError()
Const srcFolderPath As String = "C:\users\desktop\test1"
Const dstFolderPath As String = "C:\users\desktop\test2"
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(srcFolderPath) Then
MsgBox "Source Folder doesn't exist.", vbCritical, "No Source"
Exit Sub
End If
If .FolderExists(dstFolderPath) Then
Dim Sep As String: Sep = Application.PathSeparator
Dim fsoFile As Object
For Each fsoFile In .GetFolder(srcFolderPath).Files
On Error Resume Next
.CopyFile _
Source:=fsoFile.Path, _
Destination:=dstFolderPath & Sep & fsoFile.Name, _
OverwriteFiles:=False
On Error GoTo 0
Next fsoFile
Else
.CopyFolder _
Source:=srcFolderPath, _
Destination:=dstFolderPath
End If
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.