读取文件夹和文件
如何读取在指定目录中的所有文件夹及文件名?
[解决办法]
'先引用microsoft scripting RuntimePrivate Sub Command1_Click()Dim fso As New FileSystemObject Set objFolder = fso.GetFolder("E:\media") For Each Path In objFolder.SubFolders Debug.Print Path For Each Files In fso.GetFolder(Path).Files Debug.Print Files Next NextEnd Sub
[解决办法]
加强说明下1L的回答
方法一:filelist控件
添加drivelistbox、dirlistbox、filelistbox控件各一个并输入以下代码
Option ExplicitPrivate Sub Dir1_Change()File1.Path = Dir1.PathEnd SubPrivate Sub Drive1_Change()Dir1.Path = Drive1.DriveEnd Sub
[解决办法]
网上的代码
Public Function TreeSearch(ByVal sPath As String, ByVal sFileSpec As String, sFiles() As String) As Long
Dim n As Long
Static lngFiles As Long '文件数目
Dim sDir As String
Dim sSubDirs() As String '存放子目录名称
Dim lngIndex As Long
Dim lngTemp&
If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
sDir = Dir(sPath & sFileSpec)
'获得当前目录下文件名和数目
Do While Len(sDir)
lngFiles = lngFiles + 1
ReDim Preserve sFiles(1 To lngFiles)
sFiles(lngFiles) = sPath & sDir
sDir = Dir
Loop
'获得当前目录下的子目录名称
lngIndex = 0
sDir = Dir(sPath & "*.*", vbDirectory)
Do While Len(sDir)
If Left(sDir, 1) <> "." And Left(sDir, 1) <> ".." Then '' 跳过当前的目录及上层目录
'找出子目录名
If GetAttr(sPath & sDir) And vbDirectory Then
lngIndex = lngIndex + 1
'保存子目录名
ReDim Preserve sSubDirs(1 To lngIndex)
sSubDirs(lngIndex) = sPath & sDir & "\"
End If
End If
sDir = Dir
Loop
For lngTemp = 1 To lngIndex
'查找每一个子目录下文件,这里利用了递归
Call TreeSearch(sSubDirs(lngTemp), sFileSpec, sFiles())
Next lngTemp
TreeSearch = lngFiles
End Function
[解决办法]
遍历一个文件夹下的所有文件和子文件夹
Option ExplicitPublic Sub 遍历文件夹和文件(sFolder As String) Dim fs As Object On Error Resume Next Set fs = CreateObject("Scripting.FileSystemObject") File_Folder_List (fs.GetFolder(sFolder)) Set fs = NothingEnd SubPrivate Sub File_Folder_List(df As Object)'循环处理文件集合 Dim objFile As Object, objSubFolder As Object '文件集合 For Each objFile In df.Files ' ' '文件处理过程 ' ' Next objFile Set objFile = Nothing '文件夹集合 For Each objSubFolder In df.SubFolders ' ' '文件夹处理过程 ' ' File_Folder_List objSubFolder '递归循环处理文件夹 Next objSubFolder Set objSubFolder = NothingEnd Sub