Skip to content

Instantly share code, notes, and snippets.

@tasugim
Last active December 26, 2015 09:07
Show Gist options
  • Select an option

  • Save tasugim/d637976d10087826bd3c to your computer and use it in GitHub Desktop.

Select an option

Save tasugim/d637976d10087826bd3c to your computer and use it in GitHub Desktop.
指定したフォルダ配下のファイルのパスの一覧を文字列のコレクションとして取得するVBAのカスタムファンクション
' 指定したフォルダ直下のファイルのパスの一覧を文字列のコレクションとして取得する
' 引数
' folderPath: 対象フォルダ
' fileFilter: ファイルの絞り込み文字列 例) "*.xls*"(エクセルファイル)
Private Function GetFilePathCollectionFromTargetFolder(folderPath As String, Optional fileFilter As String = "*") As Collection
Dim filePathCollection As Collection
Dim fileName As String
Dim filePath As String
Set filePathCollection = New Collection
fileName = Dir(folderPath & "\" & fileFilter, vbNormal)
Do While fileName <> ""
filePath = folderPath & "\" & fileName
filePathCollection.Add (filePath)
fileName = Dir()
Loop
Set GetFilePathCollectionFromTargetFolder = filePathCollection
End Function
' 指定したフォルダ配下(サブフォルダを含む)のファイルのパスの一覧を文字列のコレクションとして取得する
' 引数
' folderPath: 対象フォルダ
' fileFilter: ファイルの絞り込み文字列 例) "*.xls*"(エクセルファイル)
Private Function GetFilePathCollectionFromTargetFolderRecursive(folderPath As String, Optional fileFilter As String = "*") As Collection
Dim filePathCollection As Collection
Dim subFolder As Object
Dim subFilePathCollection As Collection
Dim subFilePath As Variant
Set filePathCollection = GetFilePathCollectionFromTargetFolder(folderPath, fileFilter)
' サブフォルダのファイルのパスの一覧を再帰的に取得する
With CreateObject("Scripting.FileSystemObject")
For Each subFolder In .GetFolder(folderPath).SubFolders
Set subFilePathCollection = GetFilePathCollectionFromTargetFolderRecursive(subFolder.Path, fileFilter)
For Each subFilePath In subFilePathCollection
filePathCollection.Add (subFilePath)
Next subFilePath
Next subFolder
End With
Set GetFilePathCollectionFromTargetFolderRecursive = filePathCollection
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment