VBA Tree View from string

后端 未结 4 1201
梦毁少年i
梦毁少年i 2020-12-18 12:59

I would like to get tree view using excel vba.I have many String likes this

      /folderOne/fileOne
      /folderTwo/fileThree
      /folderOne/fileTwo
             


        
4条回答
  •  粉色の甜心
    2020-12-18 13:45

    Was looking for something with a hierarchy to try out some recursive stuff. Here is my solution for this question:

    Sub callTheFunction()
        '"A1:A6" = range with the values, "A10" = first cell of target range, "/" = delimiter
        Call createHierarchy(Range("A1:A6"), Range("A10"), "/")
    End Sub
    
    Sub createHierarchy(rngSource As Range, rngTarget As Range, strDelimiter As String)
        Dim dic As Object, rng As Range
        Set dic = CreateObject("scripting.dictionary")
        For Each rng In rngSource
            addValuesToDic dic, Split(rng.Value, strDelimiter), 1
        Next
        writeKeysToRange dic, rngTarget, 0, 0
    End Sub
    
    Sub addValuesToDic(ByRef dic As Object, ByVal avarValues As Variant, i As Long)
        If Not dic.Exists(avarValues(i)) Then
            Set dic(avarValues(i)) = CreateObject("scripting.dictionary")
        End If
        If i < UBound(avarValues) Then addValuesToDic dic(avarValues(i)), avarValues, i + 1
    End Sub
    
    Sub writeKeysToRange(dic As Object, rngTarget As Range, _
    ByRef lngRowOffset As Long, ByVal lngColOffset As Long)
        Dim varKey As Variant
        For Each varKey In dic.keys
            'adds "L    " in front of file if value is like "file*"
            rngTarget.Offset(lngRowOffset, lngColOffset) = IIf(varKey Like "file*", "L    " & varKey, varKey)
            lngRowOffset = lngRowOffset + 1
            If dic(varKey).Count > 0 Then
                writeKeysToRange dic(varKey), rngTarget, lngRowOffset, lngColOffset + 1
            End If
        Next
    End Sub
    

提交回复
热议问题