VBA/Excel/Access/Word/File Path/FileSystemObject
Содержание
Copying a File
<source lang="vb">
Sub Copy_AnyFile()
Dim fs As Object Dim strDb As String Set fs = CreateObject("Scripting.FileSystemObject") strDb = "C:\NewAccessDb.mdb" fs.CopyFile strDb, CurrentProject.Path & "\" Set fs = Nothing
End Sub
</source>
Delete file by using FileSystemObject
<source lang="vb">
Sub cmdDelete()
Dim myFileSystemObject As FileSystemObject Set myFileSystemObject = New FileSystemObject myFileSystemObject.DeleteFolder "c:\yourFolder" myFileSystemObject.DeleteFile "c:\yourFile" Set myFileSystemObject = Nothing
End Sub
</source>
Delete Folder by using FileSystemObject
<source lang="vb">
Sub cmdDelete()
Dim myFileSystemObject As FileSystemObject Set myFileSystemObject = New FileSystemObject myFileSystemObject.DeleteFolder "c:\yourFolder" myFileSystemObject.DeleteFile "c:\yourFile" Set myFileSystemObject = Nothing
End Sub
</source>
Display selected file information
<source lang="vb">
Private Sub cmdFileInfo_Click()
Dim myFileSystemObject As FileSystemObject, aFile As File Set myFileSystemObject = New FileSystemObject Set aFile = myFileSystemObject.GetFile("c:\test.txt") With aFile Debug.Print "Created: " & .DateCreated & vbCrLf Debug.Print "Last Accessed: " & .DateLastAccessed & vbCrLf Debug.Print "Last Modified: " & .DateLastModified & vbCrLf Debug.Print "Size: " & Format(.Size / 1000#, "#0.00") & "KB" & vbCrLf Debug.Print "Path: " & .Path & vbCrLf Debug.Print "Type: " & .Type End With Set myFileSystemObject = Nothing Set aFile = Nothing
End Sub
</source>
Listing files with a For...Each loop
<source lang="vb"> Sub FileListDemo() Dim objFSO As Object Dim objFolder As Object Dim objFile As Object Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.GetFolder("C:\") For Each objFile In objFolder.Files Debug.Print objFile.name Next objFile End Sub </source>
Recursive Search using the FileSystemObject Model
<source lang="vb">
Private Sub cmdStartSearch_Click()
Call FindFile("yourFile", "C:\", False) Unload frmSearch
End Sub Private Sub FindFile(target As String, ByVal aPath As String, foundTarget As Boolean)
Dim myFileSystemObject As FileSystemObject, curFolder As folder, folder As folder Dim folColl As Folders, file As file, fileColl As Files Set myFileSystemObject = New FileSystemObject Set curFolder = myFileSystemObject.GetFolder(aPath) Set folderList = curFolder.SubFolders Set fileList = curFolder.Files For Each file In fileList If file.name = target Then foundTarget = True frmFileSystem.lblPath.Caption = file.Path Exit Sub End If Next If Not foundTarget Then For Each folder In folderList DoEvents "Yield execution so other events may be processed If Not foundTarget Then FindFile target, folder.Path, foundTarget End If Next End If Set myFileSystemObject = Nothing Set curFolder = Nothing Set folderList = Nothing Set fileList = Nothing
End Sub
</source>