|
Option Explicit
Public Const INVALID_HANDLE_VALUE = -1 Public Const MAX_PATH = 260 Type FILETIME dwLowDateTime As Long dwHighDateTime As Long End Type Type WIN32_FIND_DATA dwFileAttributes As Long ftCreationTime As FILETIME ftLastAccessTime As FILETIME ftLastWriteTime As FILETIME nFileSizeHigh As Long nFileSizeLow As Long dwReserved0 As Long dwReserved1 As Long cFileName As String * MAX_PATH cAlternate As String * 14 End Type Type SECURITY_ATTRIBUTES nLength As Long lpSecurityDescriptor As Long bInheritHandle As Long End Type Declare Function CreateDirectory Lib "kernel32" Alias "CreateDirectoryA" _ (ByVal lpPathName As String, _ lpSecurityAttributes As SECURITY_ATTRIBUTES) As Long Declare Function CopyFile Lib "kernel32" Alias "CopyFileA" _ (ByVal lpExistingFileName As String, _ ByVal lpNewFileName As String, _ ByVal bFailIfExists As Long) As Long Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" _ (ByVal lpFileName As String, _ lpFindFileData As WIN32_FIND_DATA) As Long Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" _ (ByVal hFindFile As Long, _ lpFindFileData As WIN32_FIND_DATA) As Long Declare Function FindClose Lib "kernel32" _ (ByVal hFindFile As Long) As Long Private Sub cmdCopyFiles_Click() Dim sSourcePath As String Dim sDestination As String Dim sFiles As String Dim numCopied As Long 'set the appropriate initializing values sSourcePath = "c:\win\" sDestination = "c:\temptest\" sFiles = "*.txt" 'perform the copy and return the copied file count numCopied = rgbCopyFiles(sSourcePath, sDestination, sFiles) MsgBox numCopied & " files copied to " & sDestination End Sub Private Sub cmdEnd_Click() Unload Me End End Sub Public Function rgbCopyFiles(sSourcePath As String, sDestination As String, sFiles As String) As Long Dim WFD As WIN32_FIND_DATA Dim SA As SECURITY_ATTRIBUTES Dim r As Long Dim hFile As Long Dim bNext As Long Dim copied As Long Dim currFile As String 'Create the target directory if it doesn't exist r = CreateDirectory(sDestination, SA) 'Start searching for files in the Target directory. hFile = FindFirstFile(sSourcePath & sFiles, WFD) If (hFile = INVALID_HANDLE_VALUE) Then 'nothing to do, so bail out MsgBox "No " & sFiles & " files found." Exit Function End If 'Copy each file to the new directory If hFile Then Do 'trim trailing nulls, leaving one to terminate the string currFile = Left$(WFD.cFileName, InStr(WFD.cFileName, Chr$(0))) 'copy the file to the destination directory & increment the count r = CopyFile(sSourcePath & currFile, sDestination & currFile, False) copied = copied + 1 'just to check what's happening List1.AddItem sSourcePath & currFile 'find the next file matching the initial file spec bNext = FindNextFile(hFile, WFD) Loop Until bNext = 0 End If 'Close the search handle r = FindClose(hFile) 'and return the number of files copied rgbCopyFiles = copied End Function |