sheet that was exported Ms Access Gurus

FileSystemObject > File > Copy files from one folder to another

Use the File object (FileSystemObject, fso) to copy files from one folder to another, one at a time. Show progress to user using the Status Bar. Option to preface new filename with whatever text your specify. Option to use a mask to limit whick files are copied, like *.jpg. Default is *.*

This is not as efficient as letting Windows copy file in a batch, but may give the user more comfort to see that something is happening if there is a lot to do.

Technically, File is a different object than FileSystemObject ... but categorized like this anyway.

Quick Jump

Example

This show a list of files in the source folder, and the resulting list in the target. A file name prefix of "copy_" & Format(Date, "yymmdd") & "_" was specified.

spreadsheet with formatted data that Access created

As each file is copied, the Status Bar in the lower left corner will be updated to show while file number it is on, how many files there are in the folder, and the file name currently being copied.

Goto Top  

Code

' module name: mod_CopyFolderFilesToFolder_FileSystemObject
'  http://msaccessgurus.com/VBA/Code/fso_CopyFolderFilesToFolder.htm
'*************** Code Start *****************************************************
' Purpose  : copy files from one folder to another, show progress
' Author   : crystal (strive4peace)
' License  : below code
' Code List: www.MsAccessGurus.com/code.htm
'-------------------------------------------------------------------------------

' CopyFolderFilesToFolder

'------------------------------------------------------------------------------- '
Sub CopyFolderFilesToFolder( _ psPathSource As String _ , psPathTo As String _ , Optional psMask As String = "*.*" _ , Optional pbOverwrite As Boolean = True _ , Optional psPrefix As String = "" _ ) As Long '190811 strive4peace copy files from one folder to another 'copy will be done one file at a time, to show progress to user 'PARAMETERS ' psPathSource is the folder to copy files FROM ' psPathTo is the folder to copy files TO ' if psPrefix is specified, psPathTo MUST be terminated with a folder separator such as \ ' psMask = pattern for files to copy ' ie: *.*, my*.xls*, *.jpg ' pbOverwrite. True to overwrite file if it already exists. ' psPrefix is what to add to the beginning of the filename, if anything Dim nCount As Long _ , n As Long _ , sFilename As String _ , sPathFileTo As String _ , sMsg As String 'early binding ' reference: Microsoft Scripting Runtime ' Dim oFile As scripting.File 'late binding Dim oFile As Object CopyFolderFilesToFolder = 0 n = 0 sPathFileTo = psPathTo With CreateObject("Scripting.FileSystemObject").GetFolder(psPathSource) nCount = .Files.Count If Not nCount > 0 Then MsgBox "there are no files to copy", , "exiting" End If For Each oFile In .Files sFilename = oFile.Name If psMask = "*.*" Or sFilename Like psMask Then sMsg = "copying " & n + 1 & " of " & nCount & ": " & sFilename 'show message on Status Bar Application.SysCmd acSysCmdSetStatus, sMsg 'copy file If psPrefix <> "" Then sPathFileTo = psPathTo & psPrefix & sFilename End If oFile.Copy sPathFileTo, pbOverwrite 'number of files copied n = n + 1 CopyFolderFilesToFolder = n End If Next oFile End With 'clear the StatusBar Application.SysCmd acSysCmdClearStatus End Sub ' LICENSE ' You may freely use and share this code ' provided this license notice and comment lines are not changed; ' code may be modified provided you clearly note your changes. ' You may not sell this code alone, or as part of a collection, ' without my handwritten permission. ' All ownership rights reserved. Use at your own risk. ' ~ crystal (strive4peace) www.MsAccessGurus.com '*************** Code End ******************************************************* '-------------------------------------------------------------------------------

' call_CopyFolderFilesToFolder

'------------------------------------------------------------------------------- '
Sub call_CopyFolderFilesToFolder() '190811 strive4peace launch procedure to ' copy files from one folder to another Dim sPathSource As String _ , sPathTo As String _ , sMask As String _ , bOverwrite As Boolean _ , sPrefix As String _ , sMsg As String _ , nCount As Long sPathSource = "C:\TEMP" sPathTo = "C:\TEMP\FolderTo\" sMask = "*.*" sMask = "*.tx" bOverwrite = True sPrefix = "new_" & Format(Date, "yymmdd") & "_" 'do it! nCount = CopyFolderFilesToFolder(sPathSource, sPathTo, sMask, bOverwrite, sPrefix) If nCount = 0 Then sMsg = "No files found in " & sPathSource & " for " & sMask MsgBox sMsg, , "Nothing copied" Else sMsg = nCount & " Files copied. Open Desitnation Folder?" If MsgBox(sMsg, vbYesNo, "Done") = vbYes Then 'open desination folder Application.FollowHyperlink sPathTo End If End If End Sub

Goto Top  

Logic

Dimension variables. There are 2 code blocks to dimension oFile, one of which is commented. Late-binding, discussed below, is used

Initialize the return value to be 0 (zero) since no files have been copied yet.

Set n= 0 (zero) where n represents the number of files actually copied. since no files have been copied yet.

To avoid having to create a variable for a folder, use With CreateObject("Scripting.FileSystemObject").GetFolder(psPathSource) where psPathSource is the path of the source files.

Count the files in that location and assign to nCount.

If there aren't any files, give the user a message that there are no files to copy, and exit the function.

Loop through each file in the folder.

Construct a message for the status bar with the file number being processed, the total number of files, and the current file name. Show message in the Status Bar.

If the new file will have a prefix before the rest of the name, specify that with sPathFileTo. If there is no extra prefix, sPathFileTo is whatever was sent for psPathTo, and the file name won't change.

Once copied, increment the file counter, update the return value for the function, and loop back to the next file in the folder.

When the loop is done, clear the status bar.

There is no error handling in this code. It would be good to add it. Refer to other VBA examples on this site for good practice.

As such, there is also no cleanup, such as clearing the status bar ...

Parameters

psPathSource

the folder to copy files FROM

psPathTo

the folder to copy files TO
if psPrefix is specified, psPathTo MUST be terminated with a folder separator such as \

Optional Parameters

psMask

pattern for files to copy
other examples: my*.xls*, *.jpg, *.*x

default is "" (all files)

pbOverwrite

True (default) to overwrite file if it already exists.

psPrefix

what to add to the beginning of the filename, if anything. For instance, the calling program may use something like
"copy_" & Format(Date, "yymmdd") & "_"

default is "", which means that the file name won't change.

Late vs Early Binding

One of the libraries you can reference when writing VBA is called Microsoft Scripting Runtime and contains definitions for

The file this library is in is called scrrun.dll, which, for my installation, is located in C:\Windows\SysWOW64

Early Binding

Early Binding means that a reference library is loaded whenever an application that references it is opened.

A big bonus is that early binding gives you, the developer, the benefit of Intellisense while coding. This is super-helpful!

This is efficient when running too, since the library is pre-loaded and instantly available whenever needed.

In this case, the library is called Microsoft Scripting Runtime.

The disadvantage, however, is that early-binding makes the code version dependent. If the user isn't running the same versions, they will hit an error which could be avoided by late-binding.

Late Binding

When you deploy your application to users, it is a good idea to consider late binding. This means that whatever version of the library is available will be loaded at runtime when it is needed.

Late-binding is used in this example. Code to early-bind is there, but commented.

Goto Top  

Notes

Processing files one at a time is not as efficient as copying files in a batch, but provides an opportunity to give the user a message as each copy is done so they can see something is happening.

This page is still under construction ... as you may already realize. I need to spend some time on my Access application that formats code and makes web pages ... meanwhile, hopefully this has what you need!

Backstory

Everything stored on the computer is in a file, so it makes good sense to explore what you can do with them

Goto Top  

Reference

Object Browser

How to find out what is available in the Microsoft Scripting Runtime library from Access

An addition to the links below, and what they lead to, once you reference a library, you can use the Object Browser to see what is in it.

In the VBE (Visual Basic Editor), where you write VBA (press Alt-F11 to go there), press F2 to show the Object Browser window, or choose View, Object Browser from the menu.

In the upper left, you'll see a dropdown that says <All Libraries>. Change this to Scripting, which is an abbreviation for the library name.

In the lower left, you see Classes. One of these is File. Click on File and then on the right, you will see its members. Properties describe something about the file, like DateLastModified. Methods are actions you can do with it, like Copy.

Click Copy. Then on the bottom, you will see specific syntax:

Copy Destination As String, [OverWriteFiles As Boolean = True]

For basic references, when you press F1, you will be taken to Help. With this library, however, links to Help don't seem to be hooked up.

File object

Docs / Office VBA Reference / Language reference / Reference / Objects / FileSystemObject object

Help: File object

Copy method

Docs / Office VBA Reference / Language reference / Reference / Objects / File object / Methods / Copy

Help: Copy method

FileSystemObject object

Docs / Office VBA Reference / Language reference / Reference / Objects / FileSystemObject object

Help: FileSystemObject object

CopyFile method

Docs / Office VBA Reference / Language reference / Reference / Objects / FileSystemObject object / Methods / CopyFile

This method wasn't used in the example, but you may want to read this page anyway

Help: CopyFile method

Goto Top  

Share

Share with others ... here's the link to copy:
http://msaccessgurus.com/VBA/Code/fso_CopyFolderFilesToFolder.htm

Do you have something to say?

Share your comments! Was something not clear? Did you find a bug? Is an explanation wrong or not sufficient? Do you want the code do more (there is always more)?

Some of you write to say thanks and tell me what you're doing with Access ... its nice to hear from you. I want you to be the best you can with Access, and leverage other applications like Excel, Word, and PowerPoint ... and Windows.

Are you a developer? Do you want to share? Email to ask about getting your pages added to the code index.

Let's communicate, collaborate, and appreciate ... we all get better by sharing. Email me anytime at info@msAccessGurus.com. I love hearing from you. ~ crystal

Goto Top