VBA:使用日期和时间等参数从Scripting.FileSystemObject过滤文件

时间:2015-10-16 08:02:26

标签: vba excel-vba file-handling excel

我正在尝试编写代码来查找某个位置的XML文件列表,但该位置有太多的文件和文件夹,所以我编写了一个代码来获取从该位置到excel工作簿的xml文件列表,但我无法设置过滤器来获取文件,例如 我想获取2015年创建的文件列表 。有人请帮助我,找到下面的代码。

    Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)

    On Error Resume Next
    For Each myFile In mySource.Files        
        If InStr(1, myFile.Name, ".xml", vbBinaryCompare) Then        
            Worksheets("Filelist").Range("A6").Offset(x, 0) = myFile.Path 'Replace(myFile.Path, myFile.Name, "")                      
            x = x + 1
            End If
        Else
            Resume
        End If        
    Next
    If IncludeSubfolders Then
        For Each mySubFolder In mySource.SubFolders
            Call ListMyFiles(mySubFolder.Path, True)
        Next
    End If    
End Sub

2 个答案:

答案 0 :(得分:2)

来自https://msdn.microsoft.com/en-us/library/ke6a7czx(v=vs.84).aspx

Function ShowFileInfo(filespec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   ShowFileInfo = "Created: " & f.DateCreated
End Function

答案 1 :(得分:2)

给它一个旋转:

Sub ListMyFiles(mySourcePath)

files = Filter(Split(CreateObject("WScript.Shell").Exec("DIR """ & mySourcePath  & _
    IIf(Right(mySourcePath, 1) = "\", "", "\") & _
    "*.xml"" /T:C /S /B /A:-D /O:-D").StdOut.ReadAll, vbCrLf), ".")

For Each fil In files
    If Year(CDate(CreateObject("Scripting.FileSystemObject").GetFile(CStr(fil)).DateCreated)) = 2015 Then
        Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Value = CStr(fil)
    End If
Next

End Sub

这使用cmd.exe中的DIR命令列出所有.xml文件,然后使用FileSystemObject检查创建的日期。如果它们是在2015年创建的,那么它会在A列中列出它们。