有可能这个代码获取文件和文件夹吗?

时间:2013-02-26 17:33:24

标签: excel vba excel-vba

我目前有这段代码:

Function GetSubDir(ByVal sDir)

Dim oFS As New FileSystemObject
Dim oDir
iCount = 1
Erase subArray()
Set oDir = oFS.GetFolder(sDir)
For Each oSub In oDir.SubFolders
    MsgBox oSubPath
    GetSubDir oSub.Path
    ReDim Preserve subArray(iCount)
    subArray(iCount) = oSub.Path
    iCount = iCount + 1
Next oSub

End Function

有没有办法修改它以便获取文件和文件夹?我试过看MSDN然而它对我来说很陌生,它是一个简单的语法更改还是整个代码需要返工?感谢

2 个答案:

答案 0 :(得分:3)

我认为这很有可能 - 此示例代码显示了如何循环文件:

Sub ShowFileList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    For Each f1 in fc
        s = s & f1.name 
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub

只需添加一个For...Each周期。但是,如果要递归处理所有文件和所有子文件夹到最后一个深层次 - 这将需要更多编码。但是,Google可以在几分钟内显示大量此类ready-to-go摘要。祝你好运!

答案 1 :(得分:0)

函数GetSubDir(ByVal sDir)

Dim oFS As New FileSystemObject

Dim oDir
Dim oSub As Object
Dim i As Integer

Dim wbName As String

Set oDir = oFS.GetFolder(sDir)
For Each oSub In oDir.SubFolders
    SDCount = SDCount + 1
    ReDim Preserve wbSDName(1 To SDCount)
    wbSDName(SDCount) = oSub.Path
    GetSubDir oSub.Path
Next oSub

结束功能