Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save tasugim/4b0e695f153d9f572924 to your computer and use it in GitHub Desktop.
指定したフォルダ配下のファイルのパスの一覧を文字列の配列として取得するVBAのカスタムファンクション
' 指定したフォルダ直下のファイルのパスの一覧を文字列の配列として取得する
' 引数
' folderPath: 対象フォルダ
' fileFilter: ファイルを絞りこむためのフィルタ、初期値は"*"(全てのファイル)
' 例) "*.xls*" エクセルファイル
' ファイルが存在しない場合、空の配列を返す ※空の配列はUBoundで-1を返す
Private Function GetFilePathArrayFromTargetFolder(folderPath As String, _
Optional fileFilter As String = "*") As String()
Dim filePathArray() As String
Dim fileName As String
Dim i As Integer
fileName = Dir(folderPath & "\" & fileFilter, vbNormal)
i = 0
Do While fileName <> ""
ReDim Preserve filePathArray(i)
filePathArray(i) = folderPath & "\" & fileName
fileName = Dir()
i = i + 1
Loop
If i = 0 Then
filePathArray = Split(vbNullString, vbNullChar)
End If
GetFilePathArrayFromTargetFolder = filePathArray
End Function
' 指定したフォルダ配下、サブフォルダを含めてファイルのフルパスの一覧を文字列の配列として取得する
' 引数
' folderPath: 対象フォルダ
' fileFilter: ファイルを絞りこむためのフィルタ、初期値は"*"(全てのファイル)
' 例) "*.xls*" エクセルファイル
' ファイルが存在しない場合、空の配列を返す ※空の配列はUBoundで-1を返す
Private Function GetFilePathArrayFromTargetFolderRecursive(folderPath As String, _
Optional fileFilter As String = "*") As String()
Dim filePathArray() As String
filePathArray = GetFilePathArrayFromTargetFolder(folderPath, fileFilter)
With CreateObject("Scripting.FileSystemObject")
Dim subFolder As Object
For Each subFolder In .GetFolder(folderPath).SubFolders
Dim subFilePathArray As Variant
subFilePathArray = GetFilePathArrayFromTargetFolderRecursive(subFolder.Path, fileFilter)
' subFilePathArrayが空でない場合、filePathArrayとsubFilePathArrayを結合する
If UBound(subFilePathArray) >= 0 Then
filePathArray = Split(Join(filePathArray, "|") & "|" & Join(subFilePathArray, "|"), "|")
End If
Next subFolder
End With
GetFilePathArrayFromTargetFolderRecursive = filePathArray
End Function
@tasugim

tasugim commented Dec 26, 2015

Copy link
Copy Markdown
Author

配列ではなくコレクションを返す形で書き直した。コレクションを返すパターンの方が実装が素直で扱いやすいはず。特別な理由がない限りコレクションを返すパターンを利用することを推奨する。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment