0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Excel VBA】MkDirステートメント|フォルダを作成する方法と注意点

Last updated at Posted at 2025-09-11

この記事ではMkDirステートメントの使い方と注意点について解説します。
他のよく使うステートメント一覧はこちら。

MkDirステートメントの使い方と注意点

MkDirステートメントは、指定したパスに新しいフォルダを作成するステートメントです。
VBAからプログラム的にフォルダを作りたいときに使用します。

構文

MkDir パス
  • パス : 作成したいフォルダの完全パスまたは相対パス

使用例

フォルダを1つ作成する

Sub Sample()
    MkDir "C:\Temp\TestFolder"
End Sub

▶ 出力結果
C:\Temp\下にTestFolderというフォルダが作成されます。
sample01.png

変数で指定されたフォルダを作成

パスを変数に格納して使用することも可能です。

Sub Sample()
    Dim folderPath As String
    folderPath = "C:\Temp\MyFolder"
    
    MkDir folderPath
End Sub

▶ 出力結果
sample02.png

フォルダが存在しないときだけ作成する

Sub Sample()
    Dim folderPath As String
    folderPath = "C:\Temp\MyFolder"

    If Dir(folderPath, vbDirectory) = "" Then
        MkDir folderPath
    Else
        Debug.Print "フォルダはすでに存在します"
    End If
End Sub

▶ 出力結果(存在する場合)

フォルダはすでに存在します

⚠️注意

親フォルダが存在しないとエラー

Sub Sample()
    MkDir "C:\NotExist\SubFolder"
End Sub

▶ 出力結果(親フォルダーが存在しない場合)
error_76.png

同名のフォルダが既に存在するとエラー

Sub Sample()
    Dim folderPath As String
    folderPath = "C:\Temp\MyFolder"
    
    MkDir folderPath    ' 成功
    MkDir folderPath    ' 失敗
End Sub

▶ 出力結果
error_75.png

相対パスは現在のカレントディレクトリに依存

Sub Sample()

    Dim currentDir As String
    currentDir = CurDir()
    Debug.Print "現在の作業フォルダは: " & currentDir

    Dim folderPath As String
    folderPath = "MyFolder"
    
    MkDir folderPath
End Sub

▶ 出力結果

現在の作業フォルダは: C:\Temp

sample02.png

その他のステートメント

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?