2016-10-22 75 views
0

我在Excel中使用嘗試,但我無法得到我的確切要求。如何在Excel中獲取文件夾名稱?

例如:類別是文件夾名稱。這裏面分類我有很多文件夾一樣 AAA BBB CCC DDD EEE

如何得到AAA在Excel EEE

+1

您可以在此使用Dir()。 –

+0

如果您跳過文件夾會發生什麼 - 例如'AAA','BBB','DDD','EEE'? –

回答

0

此代碼將獲取路徑內的每個文件夾中的單元格A1中定義的名稱(如C :),並把它們列B:

Sub GetChildFolders() 
    Dim fso, categoryFolder, subFolder As Object 
    Dim i As Integer 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set categoryFolder = fso.GetFolder(Cells(1, 1).Value) 
    i = 1 
    For Each subFolder In categoryFolder.subfolders 
    Cells(i, 2) = subFolder.Name 
    i = i + 1 
    Next subFolder 
End Sub 

Alterantively,您可以創建一個新的公式,返回逗號分隔的列表與文件夾: (要創建新的配方,從添加一個新的模塊插入菜單中的VBA的窗口)

Function GetChildFoldersList(ByVal path As String) 
    Dim fso, categoryFolder, subFolder As Object 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set categoryFolder = fso.GetFolder(path) 
    For Each subFolder In categoryFolder.subfolders 
    GetChildFoldersList = GetChildFoldersList + subFolder.Name + ", " 
    Next subFolder 
    If GetChildFoldersList > 0 Then 
    GetChildFoldersList = Left(GetChildFoldersList, Len(GetChildFoldersList) - 2) 
    Else 
    GetChildFoldersList = "Folder is Empty!" 
    End If 
End Function 
+0

您可以添加對** Microsoft Scripting Runtime **(** Tools - > References ... **)的引用,然後將'Dim fso As New Scripting.FileSystemObject'寫入。 –

+0

請注意,'fso'和'categoryFolder'鍵入爲'Variant'。爲了將它們輸入爲Object,必須爲每個變量重複'As Object':Dim fso As Object,categoryFolder As Object,subFolder As Object'。 –

0

ŧ他正確處理範圍。

它不假定子文件夾按字母順序返回文件夾。 (在documentation中沒有提及這樣的事情)。

'Add a reference to 'Microsoft Scripting Runtime' (Tools -> References...) 
Function ChildFolders(path As String) As String 
    Dim fso As New Scripting.FileSystemObject 
    Dim fldr As Scripting.Folder 
    Set fldr = fso.GetFolder(path) 
    Dim minFolder As String, maxFolder As String 
    minFolder = "" 
    maxFolder = "" 
    Dim x As folder 
    For Each x In fldr.SubFolders 
     If x.Name < minFolder Or minFolder = "" Then 
      minFolder = x.Name 
     ElseIf x.Name > maxFolder Then 
      maxFolder = x.Name 
     End If 
    Next 

    Select Case True 
    Case minFolder = "" And maxFolder = "" 
     ChildFolders = "(No folders)" 
    Case maxFolder = "" 
     ChildFolders = minFolder 
    Case Else 
     ChildFolders = minFolder & " to " & maxFolder 
    End Select 
End Function 
相關問題