Create Folder by VBA in Excel

 How to create a folder in your drive automatically using VBA cade in Excel.

Sometimes we need to create a folder to save data like Pdf, jpg files. Through the excel vba you check whether folder is already exists or not. If not then vba will create the folder. for example, in some cases if you create pdf file by vba then you need to set the location where your pdf file will be saved. Very simple way You can create a programme when you open excel workbook then folder will be created automatically, goto Developer Tab >> Visual Basic >> Double click on "This WorkBook"  and make some changes as shown in picture. Now write the following codes..

Private Sub Workbook_Open()

'On Error Resume Next

If Len(Dir("c:\New Folder", vbDirectory)) = 0 Then

' if New Folder is not found in C drive then 

  MkDir "c:\New Folder"

End If

End Sub

Here I created a folder named as "New Folder" in C drive. You can change it as you wish.

 

Another Method : Create a folder at same location where your file has saved :

write a macro in visual basic and call it when file is opened same as above pic. To get the workbook path write the code (ThisWorkbook.Path & Application.PathSeparator) and write the folder name which you want to create. In my case I write the folder name as "Images" and defined a variable as string( in my case, it is strFolder. Now apply condition if the folder does not exist at same location by (If Dir(strFolder, vbDirectory) = "" Then)   then vba will create the folder. So you need to use MkDir function as MkDir strFolder

Sub CreateFolder()

    Dim strFolder As String

    strFolder = ThisWorkbook.Path & Application.PathSeparator & "Images"

    If Dir(strFolder, vbDirectory) = "" Then   

        MkDir strFolder

    End If

End Sub


No comments:

Post a Comment