ファイルパスの配列からUserFormのTreeViewコントロールにツリー構造を表示するVBAコードを紹介します。たとえば C:\Users\Sample\file1.xlsx
のようなパスをツリー表示するイメージです。
1. フォームの準備
まず、UserForm(例: UserForm1
)に TreeViewコントロール(Microsoft TreeView Control) を追加します。
- ツールボックスで
TreeView
を追加(※「Microsoft Windows Common Controls 6.0 (SP6)」の参照が必要) - TreeView の
Name
はTreeView1
にしておく
2. コード例(パス配列 → TreeView)
Private Sub LoadTreeViewFromPaths(filePaths As Variant)
Dim nodeDict As Object
Set nodeDict = CreateObject("Scripting.Dictionary")
Dim i As Integer
Dim parts() As String
Dim currentPath As String
Dim parentKey As String
Dim nodeKey As String
Dim j As Integer
Me.TreeView1.Nodes.Clear
For i = LBound(filePaths) To UBound(filePaths)
parts = Split(filePaths(i), "\")
currentPath = ""
parentKey = ""
For j = LBound(parts) To UBound(parts)
If currentPath = "" Then
currentPath = parts(j)
Else
currentPath = currentPath & "\" & parts(j)
End If
nodeKey = currentPath
' ノードが未登録なら追加
If Not nodeDict.Exists(nodeKey) Then
If parentKey = "" Then
Me.TreeView1.Nodes.Add , , nodeKey, parts(j)
Else
Me.TreeView1.Nodes.Add parentKey, tvwChild, nodeKey, parts(j)
End If
nodeDict.Add nodeKey, True
End If
parentKey = nodeKey
Next j
Next i
End Sub
3. 呼び出し例
以下のようにフォームの Initialize
イベントや任意のボタンで呼び出します:
Private Sub UserForm_Initialize()
Dim files As Variant
files = SelectMultipleFiles() ' 前述の関数と組み合わせ可
If IsArray(files) Then
LoadTreeViewFromPaths files
End If
End Sub
4. 表示例(ツリー構造)
C:
└─ Users
└─ Sample
├─ file1.xlsx
└─ file2.xlsx
補足
Scripting.Dictionary
を使ってノードの重複追加を防止Split(path, "\")
でフォルダ階層を順に処理- TreeViewにノード追加時は、親ノードのキーを指定して階層化
コメント