ファイルを分類して整理したあと、「元のファイルパス」と「新しいファイルパス」をツリービューに表示することで、整理の結果を視覚的に確認できます。
この記事では、VBAのフォームにある TreeView
コントロールを使って、分類結果を表示する方法をご紹介します。
使用する配列の構成
まず、ツリービューに表示するためには、以下のような2次元配列を用意します。
配列の構成
この配列を使って、1行ごとに「どのファイルをどこに移動したか」を記録します。
配列の要素 | 内容 | 例 |
---|---|---|
配列(i, 0) | 元のファイルのパス | C:\Documents\10-Report.docx |
配列(i, 1) | 分類後の(移動先)ファイルのパス | C:\整理済み\Group_10\10-Report.docx |
表示イメージ
ツリービューA(元のファイルパス)
C:\
└─ Documents
├─ 10-Report.docx
├─ 23-Summary.txt
└─ abc.txt
ツリービューB(新しいファイルパス)
C:\
└─ 整理済み
├─ Group_10
│ └─ 10-Report.docx
├─ Group_20
│ └─ 23-Summary.txt
└─ その他
└─ abc.txt
ツリービューに表示するVBAコード例
以下は、分類結果を TreeView
コントロールに表示するためのサンプルコードです。
' TreeViewにファイルパスを階層表示する処理
Sub ShowPathsInTreeViews(dataArray As Variant, tvA As TreeView, tvB As TreeView)
Dim i As Long
Dim originalPath As String
Dim newPath As String
' 初期化
tvA.Nodes.Clear
tvB.Nodes.Clear
' ツリービューへ追加(配列行数分)
For i = LBound(dataArray, 1) To UBound(dataArray, 1)
originalPath = dataArray(i, 0)
newPath = dataArray(i, 1)
Call AddPathToTreeView(tvA, originalPath)
Call AddPathToTreeView(tvB, newPath)
Next i
End Sub
' ファイルパスを1行ずつツリービューに追加する処理
Sub AddPathToTreeView(tv As TreeView, filePath As String)
Dim parts() As String
Dim i As Long
Dim currentKey As String
Dim parentKey As String
Dim nodeText As String
parts = Split(filePath, "\")
parentKey = ""
For i = 0 To UBound(parts)
nodeText = parts(i)
currentKey = parentKey & "\" & nodeText
On Error Resume Next
If tv.Nodes(currentKey) Is Nothing Then
tv.Nodes.Add Key:=currentKey, Text:=nodeText, Relative:=IIf(parentKey = "", "", parentKey), _
Relationship:=IIf(parentKey = "", tvwRoot, tvwChild)
End If
On Error GoTo 0
parentKey = currentKey
Next i
End Sub
フォーム構成のポイント
TreeViewA
:元のファイルパス表示用TreeViewB
:新しいファイルパス表示用CommandButton
:処理開始(データを表示)
配置例イメージ(フォーム)
おわりに
この方法を使えば、ファイルの整理結果をフォルダ構造ごとに可視化することができ、処理の確認やユーザーへの説明もスムーズに行えます。
分類処理のログとしても活用できますので、ぜひ応用してみてください!
コメント