- Excelから自動でフォルダを作成したい
- ユーザーにフォルダ選択させたい
- フォルダ内のファイル名を一括取得したい
- 作成したフォルダをすぐに開きたい
今回は「VBAでフォルダ操作を一気にこなす方法」をシェアします。
この記事を読めば、VBAでフォルダまわりの操作がまるっと自動化できます。
Contents
【まずは基本】VBAでフォルダを作成するコード
Sub CreateFolder()
Dim folderPath As String
folderPath = "C:\Users\YourName\Desktop\TestFolder"
If Dir(folderPath, vbDirectory) = "" Then
MkDir folderPath
MsgBox "フォルダを作成しました!"
Else
MsgBox "すでにフォルダがあります!"
End If
End Sub
【応用①】VBAでフォルダを選択するダイアログを出す方法
Function SelectFolder() As String
Dim folderDialog As FileDialog
Set folderDialog = Application.FileDialog(msoFileDialogFolderPicker)
If folderDialog.Show = -1 Then
SelectFolder = folderDialog.SelectedItems(1)
Else
SelectFolder = ""
End If
End Function
これを呼び出すだけで、GUIでフォルダを選べるダイアログが出ます。
例えばこう使います👇
Sub TestSelectFolder()
Dim path As String
path = SelectFolder()
MsgBox "選択されたフォルダは:" & path
End Sub
【応用②】VBAでフォルダ内のファイル名を一括取得する方法
Sub GetFileNamesInFolder()
Dim folderPath As String
Dim fileName As String
Dim i As Long
folderPath = SelectFolder() & "\"
If folderPath = "\" Then Exit Sub
fileName = Dir(folderPath & "*.*")
i = 1
Do While fileName <> ""
Cells(i, 1).Value = fileName
fileName = Dir
i = i + 1
Loop
End Sub
【応用③】作成したフォルダをエクスプローラーで開く方法
Sub OpenCreatedFolder()
Dim folderPath As String
folderPath = "C:\Users\YourName\Desktop\TestFolder"
If Dir(folderPath, vbDirectory) <> "" Then
Shell "explorer.exe """ & folderPath & """", vbNormalFocus
Else
MsgBox "フォルダが見つかりません!"
End If
End Sub
このコードで、フォルダを自動で開くことができます。
地味だけど超便利です。
まとめ:VBAでフォルダ操作は全部自動化できる
今回紹介したVBAテクをまとめます👇
操作内容 | コード例 |
---|---|
フォルダ作成 | MkDir + Dir |
フォルダ選択 | FileDialog(msoFileDialogFolderPicker) |
ファイル名取得 | Dir() でループ |
フォルダを開く | Shell "explorer.exe" |
おまけ:すべて組み合わせて時短マクロに!
最後に、これらを組み合わせて「選んだフォルダ内に日付フォルダを作って、開く」マクロも紹介しておきます👇
Sub CreateDateFolderAndOpen()
Dim basePath As String
Dim newFolder As String
basePath = SelectFolder()
If basePath = "" Then Exit Sub
newFolder = basePath & "\" & Format(Now, "yyyymmdd")
If Dir(newFolder, vbDirectory) = "" Then
MkDir newFolder
End If
Shell "explorer.exe """ & newFolder & """", vbNormalFocus
End Sub
これだけで、日付付きのフォルダが自動でできて、そのまま開いてくれる。
地味だけど、やってみると超気持ちいいです(笑)
コメント