copy file via Access VBA

  • Thread starter Thread starter Dan
  • Start date Start date
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
 
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 <--
 
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
 
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 <--
 
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
 
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.
 
Hi everyone,

I am trying to do something similar to this post. Basically I am simply copying a csv file from a source folder into another destination folder. I am using this code in a button to copy the file:

CopyFile "C:\source\sourcefile.csv", "C:\destination\destinationfile.csv", True


It is working fine. My only problem is that I want the destination file to be overwritten always. What changes do I need to make to that code to be able to overwrite the destination file ?

Appreciate your help.
 
Back
Top