Skip to Content

Create Folder using VBA


To create a folder using VBA, you can use the MkDir function. 

Here's an example code snippet that creates a folder in a specified location:

VBA Code to Create a Folder:

Sub CreateFolder() Dim folderPath As String ' Specify the folder path folderPath = "C:\NewFolder" ' Check if the folder already exists If Dir(folderPath, vbDirectory) = "" Then ' Create the folder MkDir folderPath MsgBox "Folder created successfully at " & folderPath, vbInformation Else MsgBox "Folder already exists at " & folderPath, vbExclamation End If End Sub

Explanation Step by Step:

  1. Sub CreateFolder()
    • Declares a subroutine named CreateFolder.
  2. Dim folderPath As String
    • Declares a variable folderPath to hold the path of the folder you want to create. This variable is a String type.
  3. folderPath = "C:\Users\YourUsername\Documents\MyNewFolder"
    • Assigns the full folder path to the variable folderPath. Replace "YourUsername" with your actual username and update the path as needed.
  4. If Dir(folderPath, vbDirectory) = "" Then
    • Uses the Dir function to check if a folder exists at the specified path.
      • vbDirectory is a constant that ensures Dir checks for a directory.
      • If Dir returns an empty string (""), it means the folder does not exist.
  5. MkDir folderPath
    • The MkDir statement creates the folder at the specified folderPath.
  6. MsgBox "Folder created successfully at: " & folderPath
    • Displays a message box to confirm the folder creation.
  7. Else
    • If the folder already exists, the code moves to the Else block.
  8. MsgBox "Folder already exists at: " & folderPath
    • Displays a message box indicating that the folder already exists.
  9. End If
    • Ends the If statement.
  10. End Sub
    • Ends the subroutine.

How to Use:

  1. Open Excel.
  2. Press Alt + F11 to open the VBA Editor.
  3. Go to Insert > Module to insert a new module.
  4. Paste the code into the module.
  5. Update the folderPath variable with the desired folder location.
  6. Close the VBA editor and press Alt + F8 in Excel to run the macro CreateFolder.


in VBA
RKsTechAdemy 28 November 2024
Share this post
Archive
Sign in to leave a comment
Building Custom Functions in Excel Using VBA