0

I need to check a folder for a file, if it exists delete it an replace it with an updated version, or if the file doesn't delete then it will copy the file from a path into the individuals personal drive

My Code:

Dim FileExistsbol As Boolean
Dim stFileName As String
Dim CopyFrom As String
Dim CopyTo As String

stFileName = "H:\Test File.txt"
stFileName = Trim(stFileName)
FileExistsbol = dir(stFileName) <> vbNullString

If FileExistsbol Then
 Kill stFileName
 CopyFrom = "J:\Test File.txt"
 CopyTo = "H:\"
 FileSystemObject.CopyFile CopyFrom, CopyTo
Else
 CopyFrom = "J:\Test File.txt"
 CopyTo = "H:\"
 FileSystemObject.CopyFile CopyFrom, CopyTo
End If

What Happens:

The code executes and deletes the existing file as expected, but it appears to be failing on the copy and paste part.

Error:

The debug that comes up is:

Object Required

dmorgan20
  • 353
  • 8
  • 33

2 Answers2

2

Bare bones:

Dim fso As Object       'filesystemobject    
Set fso = CreateObject("Scripting.FileSystemObject")    
fso.CopyFile strSourcePathWithFileAndExt, strDestPathWithFinalBackslash    
Set fso = Nothing
wazz
  • 4,953
  • 5
  • 20
  • 34
1

You haven't said which line is throwing the error, but I noticed that you don't seem to have instantiated a new FileSystemObject:

dim fso as Object
set fso=CreateObject("Scripting.FileSystemObject")

then use the fso reference to copy your file

fso.CopyFile CopyFrom, CopyTo

The method above used "Late binding" to interrogate the registry for Scripting.FileSystemObject

You can also use early binding and reference the Microsoft Scripting Runtime directly and avoid the use of CreateObject

This is detailed in this Stack Overflow answer: https://stackoverflow.com/a/3236348/491557

Spangen
  • 4,420
  • 5
  • 37
  • 42