Skip to content

Instantly share code, notes, and snippets.

@YujiFukami
Created January 17, 2024 08:45
Show Gist options
  • Save YujiFukami/7cf58f2b14f63757708b1a1370fef13a to your computer and use it in GitHub Desktop.
Save YujiFukami/7cf58f2b14f63757708b1a1370fef13a to your computer and use it in GitHub Desktop.
Public Function GetFiles(ByRef FolderPath As String, _
ParamArray Extensions() As Variant) _
As Variant
'フォルダ内のファイルを一覧で取得する
'「Microsoft Scripting Runtime」ライブラリを参照すること
'20231218 リファクタリング
'引数
'FolderPath・・・検索対象のフォルダパス
'Extensions・・・取得対象の拡張子、可変長引数配列で入力
'参考
'https://www.softex-celware.com/post/getfiles
'返り値
'ファイル名一覧の一次元配列
'ファイルが1つもなかったらEmptyを返す
'※※※※※※※※※※※※※※※※※※※※※※※※※※
'引数チェック
'フォルダの確認
Dim FSO As New FileSystemObject
If FSO.FolderExists(FolderPath) = False Then
MsgBox "「" & FolderPath & "」" & vbLf & _
"のフォルダの存在が確認できません。" & vbLf & _
"処理を終了します。", vbExclamation
Exit Function
End If
'※※※※※※※※※※※※※※※※※※※※※※※※※※
'処理
'拡張子の連想配列を作成
Dim ExtensionDict As New Dictionary
Dim TmpExtension As String
Dim I As Long
For I = 0 To UBound(Extensions, 1)
TmpExtension = Extensions(I)
'小文字に変換
TmpExtension = StrConv(TmpExtension, vbLowerCase)
ExtensionDict.Add TmpExtension, ""
Next
'フォルダ内の各ファイルを取得して、対象の拡張子だけ配列に格納
Dim Folder As Scripting.Folder
Set Folder = FSO.GetFolder(FolderPath)
Dim File As Scripting.File
Dim FileExtension As String
Dim FileName As String
Dim K As Long: K = 0
Dim N As Long
Dim Output As Variant: ReDim Output(1 To 1)
If Folder.Files.Count = 0 Then
'ファイルが1つもなかったらEmptyを返す
Exit Function
End If
For Each File In Folder.Files
FileName = File.Name 'ファイル名を取得
'拡張子を取得して小文字に変換
FileExtension = FSO.GetExtensionName(FileName)
FileExtension = StrConv(FileExtension, vbLowerCase)
If ExtensionDict.Exists(FileExtension) = True Then
K = K + 1
ReDim Preserve Output(1 To K)
Output(K) = FileName
End If
Next
'※※※※※※※※※※※※※※※※※※※※※※※※※※
'出力
GetFiles = Output
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment