copy file via Access VBA

D

Dan

How can I make a copy of C:\Source\test.txt to C:\CopyLoc\
but if test.txt already exist in C:\CopyLoc\ not to do anything.

Thanks,
Dan
 
S

Stefan Hoffmann

hi Dan,

How can I make a copy of C:\Source\test.txt to C:\CopyLoc\
but if test.txt already exist in C:\CopyLoc\ not to do anything.
Use this Win32 API function:

Public Declare Function CopyFile Lib "kernel32" Alias "CopyFileA" ( _
ByVal AExistingFileName As String, _
ByVal ANewFileName As String, _
ByVal AFailIfExists As Boolean _
) As Boolean

Copy it in a standard module and simply use it as:

CopyFile "C:\Source\test.txt", "C:\CopyLoc\test.txt", True


mfG
--> stefan <--
 
P

Paolo

Hi Dan,
this is one way

Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists("C:\CopyLoc\text.txt") Then
msgbox "Test.txt already present in c:\copyloc"
else
fs.copyfile "C:\Source\test.txt" "c:\copyloc\"
End If
set fs=nothing

this is another way to do the same

if dir("c:\copyloc\test.txt")="" then ''the file doesn't exist in c:\copyloc
filecopy "C:\Source\test.txt" "c:\copyloc\test.txt"
endif

all this is aircode

HTH Paolo
 
S

Stefan Hoffmann

hi Paolo,

this is one way
this is another way to do the same
Not really, both solutions have the same problem: Timing.

Right after checking for the non-existence of the file any other process
may create this file. Then your FileCopy will still fail.


mfG
--> stefan <--
 
P

Paolo

Good point Stefan, I didn't think about timing...
In some cases that could create some problems that using the API function
could avoid. Thanks for the feedback
 
D

Dirk Goldgar

Paolo said:
Good point Stefan, I didn't think about timing...
In some cases that could create some problems that using the API function
could avoid. Thanks for the feedback


On the other hand, the FileSystemObject.CopyFile method does have an
<overwrite> argument that can be specified as False to prevent overwriting
an existing file. If you try, an error will be raised, that one would
presumably want to trap in the code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top