Jim
Jim

Reputation: 13

Cross check files in two folders

I have two folders: Master folder & New folder. Files in two folders share the same file name. I need to cross check the files between these two folders.

With the code below, I can append data. But it fails to import file. The script shows no error message. I just don't know what went wrong.

On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set SrcFolder = fso.GetFolder("C:\Users\Vault Keeper\Desktop\NewFile")
DestFolder = "C:\Users\Vault Keeper\Desktop\MasterFile"

For Each NewFile in SrcFolder.files
    If fso.FileExists(DestFolder & "\" & NewFile.name) Then
        txt = NewFile.OpenAsTextStream(1).ReadAll
        Set MasterFile = FSO.OpenTextFile(DestFolder & "\" & NewFile.name, 8)
        MasterFile.Write txt
    Else
        fso.CopyFile "C:\Users\Vault Keeper\Desktop\NewFile" & "\" & NewFile.name, _
            DestFolder
    End If
Next

Upvotes: 1

Views: 770

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

It's rather unsurprising that you don't know what went wrong when you tell your script to shut up about whatever's going wrong (On Error Resume Next). Remove that line (using global OERN is a terrible practice anyway) and see what error you get.

Most likely the error is "permission denied", because you're trying to copy a file to an existing destination folder without that path ending with a backslash:

DestFolder = "C:\Users\Vault Keeper\Desktop\MasterFile"   '<-- no trailing backslash
...
fso.CopyFile "C:\Users\Vault Keeper\Desktop\NewFile" & "\" & NewFile.name, DestFolder

Quoting from the documentation:

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. In either case, three things can happen when an individual file is copied.

  • If destination does not exist, source gets copied. This is the usual case.
  • If destination is an existing file, an error occurs if overwrite is false. Otherwise, an attempt is made to copy source over the existing file.
  • If destination is a directory, an error occurs.

Append a backslash to the destination path, and the error should vanish. Also, since you already have a File object, I'd recommend to use its Copy method rather than CopyFile:

NewFile.Copy DestFolder & "\"

Upvotes: 1

san-san
san-san

Reputation: 64

You can check file using this

Dim objFSO As Scripting.FileSystemObject

If objFSO Is Nothing Then Set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FileExists(fileNameAndPath) Then
    'code here...
End If

Upvotes: 0

Related Questions