Visual Basic Tips


フォルダの検索(サブフォルダ含む)


指定したフォルダの中をサブフォルダも含めて検索します。

下のサンプルをC:¥Windowsで検索すると、上のリストボックス(フォルダ一覧)にWindowsフォルダ以下のフォルダがサブフォルダも含めて出力され、下のリストボックスには上で出力されたフォルダ内の全ファイル(通常ファイルのみ)が出力されます。

Private Sub Form_Load()
  
Dim i As Integer
  
Dim colFolder As Collection
  
Dim colFile As Collection

  
Set colFolder = New Collection
  
Set colFile = New Collection

  'フォルダの検索(colFolderにはフォルダのパス名が格納されます。)
  Call FolderSearch("c:\windows", colFolder)
  'ファイルの検索(colFileにはファイルのパス名が格納されます。)
  Call FileSearch(colFolder, colFile)

  'リストボックスにcolFolderの内容とcolFileの内容を出力します。
  LstFolder.Visible = False
  LstFile.Visible =
False

  
For i = 1 To colFolder.Count
    LstFolder.AddItem colFolder.Item(i)
  
Next
  
For i = 1 To colFile.Count
    LstFile.AddItem colFile.Item(i)
  
Next

  LstFolder.Visible =
True
  LstFile.Visible =
True

  
Set colFolder = Nothing
  
Set colFile = Nothing
End Sub

Sub FolderSearch(strPath As String, colFolder As Collection)
  
Dim str1 As String
  
Dim str2 As String

  
If Right(strPath, 1) <> "\" Then
    strPath = strPath & "\"
  
End If

  str1 = Dir(strPath, vbDirectory)

  
Do Until str1 = ""
    
If str1 = "." Or str1 = ".." Then
    
Else
      
If GetAttr(strPath & str1) And vbDirectory Then
        colFolder.Add strPath & str1
        
Call FolderSearch(strPath & str1, colFolder)
        str2 = Dir(strPath, vbDirectory)
        
Do Until str2 = str1
          str2 = Dir
        
Loop
      
End If
    
End If
    str1 = Dir
  
Loop
End Sub

Sub FileSearch(colFolder As Collection, colFile As Collection)
  
Dim i As Integer
  
Dim str As String
  
Dim strPath As String

  
For i = 1 To colFolder.Count
    strPath = colFolder.Item(i)
    
If Right(strPath, 1) <> "\" Then
      strPath = strPath & "\"
    
End If
    str = Dir(strPath, vbNormal)
'通常ファイルを検索
    
Do Until str = ""
      colFile.Add strPath & str
      str = Dir
    
Loop
  
Next
End Sub


DownLoad vbtips068.lzh 3KB (VB6.0)