【问题标题】:Using VBA FileSystemObject, specific file File extension使用 VBA FileSystemObject,特定文件 文件扩展名
【发布时间】:2016-11-16 05:37:18
【问题描述】:

我正在使用以下代码列出文件夹及其子文件夹中所有扩展名为 xls、xlsx 或 xlsm 的文件。以下代码有效,但问题是,它列出了子文件夹中具有所有扩展名的所有文件,但仅列出了主文件夹中的 excel 文件。我无法弄清楚这段代码有什么问题。你能帮帮我吗?

Sub List_XL_Files(ByVal SheetName As String, ByVal SourceFolderName As String, ByVal IncludeSubfolders As Boolean)

Dim FSO As Object
Dim SourceFolder As Object
Dim SubFolder As Object
Dim FileItem As Object
Dim lRoMa As Long

Set FSO = CreateObject("Scripting.FileSystemObject")
Set SourceFolder = FSO.GetFolder(SourceFolderName)

lRoMa = ThisWorkbook.Sheets(SheetName).Cells(Rows.Count, 2).End(xlUp).Row + 1
ReDim arrFolders(ctr)

With ThisWorkbook.Sheets(SheetName)
    For Each FileItem In SourceFolder.Files
           strFileExt = FSO.GetExtensionName(FileItem)
           If strFileExt = "xlsm" Or strFileExt = "xlsx" Or strFileExt = "xls" Then
                MsgBox strFileExt
                .Cells(lRoMa + r, 1).Value = lRoMa + r - 7
                .Cells(lRoMa + r, 2).Formula = strFileExt
                .Cells(lRoMa + r, 3).Formula = FileItem.Name
                .Cells(lRoMa + r, 4).Formula = FileItem.Path
                .Cells(lRoMa + r, 5).Value = "-"
                .Cells(lRoMa + r, 6).Value = ""
                .Cells(lRoMa + r, 7).Value = ""
                 r = r + 1                                      ' next row number
                 X = SourceFolder.Path
           End If
    Next FileItem
End With

If IncludeSubfolders Then
    For Each SubFolder In SourceFolder.SubFolders
        ListFilesInFolder SheetName, SubFolder.Path, True
    Next SubFolder
End If

Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing

End sub

谢谢

【问题讨论】:

  • 没有错。它正确检索所有 xl 文件。
  • 将一些pdf与excel文件一起添加到您的文件夹和子文件夹中,然后重试。主要问题是子文件夹具有不同的或pdf文件..

标签: excel vba file directory filesystemobject


【解决方案1】:

For Each SubFolder In SourceFolder.SubFolders之后添加以下代码

Call List_XL_Files(SheetName, SubFolder.Path, True)

会有用的

【讨论】:

  • 谢谢 ..我忘了在那里改变。我有这个代码的两个版本。
  • 有时会发生。
猜你喜欢
  • 2013-12-23
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多