프로젝트 및 실습/VBA

[VBA] TreeView(2): File Structure에서 Folder, File 실행

jooona 2022. 9. 22. 18:50
반응형

지난 글에서 TreeView에 File Structure를 띄우는 방법을 알아보았습니다. 이번 글에서는 TreeView에서 폴더 또는 파일을 클릭해서 선택된 노드를 실행하는 코드를 작성해 보겠습니다.

 

<지난 글: [VBA] TreeView(1): File Structure 출력]>

 

https://jooona.tistory.com/215

 

[VBA] TreeView(1): File Structure 출력

TreeView를 이용해 File Structure를 출력하기 위해선 먼저 두 가지 작업을 해주어야 합니다. 1. Userform 도구 상자에 TreeView 추가하기 1. 도구 상자에서 우클릭 후 [추가 컨트롤]을 클릭. 2. "Microsoft Tree..

jooona.tistory.com

 

 

지난 글에서 작성한 코드를 조금만 손보면 쉽게 기능을 구현할 수 있습니다.

 

 

지난 글에서 생성한 UserForm의 하단에 Path를 띄워줄 Label 하나와 해당 Path의 폴더 또는 파일을 실행하기 위한 Button을 하나 추가해줍니다. (색깔을 조금 추가해줬습니다 ㅎㅎ)

 

저는 Label의 이름은 PathLbl, Button의 이름은 Exec_Btn으로 지정해주었습니다.

 

그리고 아래와 같이 코드를 작성해 줍니다.

 

Private Sub make_tree()

    Dim root_path As String
    root_path = "D:\Build"    'Write Path that You Want to Set to Root
    
    PathTrv.Nodes.Clear
    PathTrv.Nodes.Add , , "NODE", root_path

    Call recursive_make_tree(root_path, "NODE")
   
End Sub


Private Sub recursive_make_tree(parent_path As String, parent_Key As String)
    
    Dim FSO, now_folder, next_folder, next_file As Variant
    Dim count As Long
    Dim child_Key As String
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    
    If FSO.FolderExists(parent_path) Then
        
        count = 0
        
        Set now_folder = FSO.GetFolder(parent_path)
        
        For Each next_folder In now_folder.SubFolders
        
            child_Key = parent_Key & "_" & CStr(count)
            PathTrv.Nodes.Add parent_Key, tvwChild, child_Key, next_folder.name
        
            Call recursive_make_tree(next_folder.path, child_Key)
            
            count = count + 1
        
        Next
        
        For Each next_file In now_folder.Files
        
            child_Key = parent_Key & "_" & CStr(count)
            PathTrv.Nodes.Add parent_Key, tvwChild, child_Key, next_file.name
        
            count = count + 1
        
        Next
        
    End If
    
End Sub


   '[START] Newly added code


Private Sub PathTrv_NodeClick(ByVal Node As MSComctlLib.Node)
    
    PathLbl.Caption = Node.FullPath
    
End Sub


Private Sub ExecBtn_Click()

    Dim FSO As New FileSystemObject
    Dim exec_path As String
    
    exec_path = PathLbl.Caption
    
    If PathLbl.Caption = "Path" Then
    
        Exit Sub
        
    End If
    
    If FSO.FolderExists(exec_path) Then
    
        Shell "Explorer.exe " & exec_path, vbNormalFocus
        
    ElseIf FSO.FileExists(exec_path) Then
    
        Shell "rundll32.exe url.dll,FileProtocolHandler " & exec_path, vbNormalFocus
    
    Else
    
        MsgBox "[Error] Chosen Folder or File cannot execute"
    
    End If
   
End Sub


   '[END] Newly added code


Private Sub RunBtn_Click()

    make_tree
    
End Sub

 

* 지난 코드에서 주석 Newly added code로 감싸진 부분만 추가되었습니다.

 

 

* 코드 설명

 

PathTrv_NodeClick 함수

 

1. TreeView에서 특정 노드가 클릭되면 실행됩니다.

2. 선택된 노드의 전체 경로를 PathLbl에 작성해줍니다.

 

 

ExecBtn_Click 함수

 

1. ExecBtn 버튼이 클릭되면 실행됩니다.

2. PathLbl에 작성된 경로를 가져와서 폴더인지, 파일인지 여부를 확인한 후 실행합니다.

3. PathLbl에 초기 Caption인 "Path"가 적혀있으면, 아무 노드도 선택되지 않은 것으로 간주하고 아무런 기능도 수행하지 않습니다.

 

* 폴더의 경우, 해당 경로의 폴더를 열어줍니다.

** 파일의 경우, 해당 파일을 실행합니다.

*** 실행할 수 없는 폴더 또는 파일일 경우 MsgBox를 통해 에러 메시지를 출력합니다.   

 

 

결과는 다음과 같습니다.

 

폴더를 선택한 뒤 [Execute] 버튼 클릭

 

파일을 선택한 뒤 [Execute] 버튼 클릭

 

반응형