下面的我的VBA代码在驱动器C:中搜索所有文件,并在Sheet(1)中列出它们。现在,我的任务是仅查找特定的.txt文件。我尝试修改代码,但没有成功。我以为这与ObjFile有关。
Sub ListAllFiles()
Dim ObjFSO As Scripting.FileSystemObject
Dim objFolder As Scripting.Folder
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = ObjFSO.GetFolder("C:\")
Call getfiledetails(objFolder)
End Sub
Function getfiledetails(objFolder As Scripting.Folder)
Dim objFile As Scripting.File
Dim nextRow As Long
Dim objSubFolder As Scripting.Folder
nextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
For Each objFile In objFolder.Files
On Error Resume Next
Cells(nextRow, 1) = objFile.Name
Cells(nextRow, 2) = objFile.Path
Cells(nextRow, 3) = objFile.Type
Cells(nextRow, 4) = objFile.DateCreated
Cells(nextRow, 5) = objFile.DateLastModified
nextRow = nextRow + 1
Next objFile
For Each objSubFolder In objFolder.SubFolders
Call getfiledetails(objSubFolder)
Next
End Function
任何帮助将不胜感激
答案 0 :(得分:2)
使用DIR
可能会有一点性能优势,但是如果您想使用现有代码,则对getfiledetails
子项的以下调整将为您提供所需的输出:
Function getfiledetails(objFolder As Scripting.Folder)
Dim objFile As Scripting.File
Dim nextRow As Long
Dim objSubFolder As Scripting.Folder
nextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
On Error Resume Next
For Each objFile In objFolder.Files
If objFile.Type = "Text Document" Then
Cells(nextRow, 1) = objFile.Name
Cells(nextRow, 2) = objFile.Path
Cells(nextRow, 3) = objFile.Type
Cells(nextRow, 4) = objFile.DateCreated
Cells(nextRow, 5) = objFile.DateLastModified
nextRow = nextRow + 1
End If
Next objFile
For Each objSubFolder In objFolder.SubFolders
Call getfiledetails(objSubFolder)
Next
End Function
如果您需要多个文档类型,例如..p
If objFile.Type = "Microsoft Word Document" Or objFile.Type = "Text Document" Then