EXCEL macro : Creating folder

In this post, I will write some coding on how to check if folder exits, creating folder and opening the folder.This example folder will be name TEST and created on desktop

For this example I'll show how to do it one by one for easy understanding.
However you can actually combine the code into one sub.

Checking if folder exist
==================================================
 Sub Check_folder()  
 Dim FSO As Object  
 Set FSO = CreateObject("scripting.filesystemobject")  
 FolderPath = "C:\"  
 PathName = Environ("userprofile") 'this will detect current pc user  
 FolderPath1 = PathName & "\Desktop\TEST"  
 If FSO.FolderExists(FolderPath1) = False Then  
 MsgBox ("Folder not exist")  
 End If  
 If FSO.FolderExists(FolderPath1) = True Then  
 MsgBox ("Folder existed")  
 End If  
 End Sub  
==================================================

Creating folder
==================================================
 Sub Create_folder()  
 Dim FSO As Object  
 Set FSO = CreateObject("scripting.filesystemobject")  
 FolderPath = "C:\"  
 PathName = Environ("userprofile")  
 FolderPath1 = PathName & "\Desktop\TEST"  
 If FSO.FolderExists(FolderPath1) = False Then  
 MkDir (FolderPath1)  
 MsgBox ("Folder ") & FolderPath1 & (" Created")  
 End  
 End If  
 If FSO.FolderExists(FolderPath1) = True Then  
 MsgBox FolderPath1 & " already exist"  
 End  
 End If  
 End Sub  
==================================================

Opening folder
==================================================
 Sub Open_folder()  
 FolderPath = "C:\"  
 PathName = Environ("userprofile")  
 FolderPath1 = PathName & "\Desktop\TEST"  
 ActiveWorkbook.FollowHyperlink Address:=FolderPath1, NewWindow:=True  
 End Sub  
==================================================

Besides hard coding the folder name, you can also use cell value for the folder name.
Sheet1(which sheet you want to use as reference).Cells(i, j)(Which cells you want to refer).Value
You can refer below coding for the example.

Checking if folder exist (using cell reference)
==================================================
 Sub Check_folder_cell()  
 Dim FSO As Object  
 Set FSO = CreateObject("scripting.filesystemobject")  
 FolderPath = "C:\"  
 PathName = Environ("userprofile")  
 FolderPath1 = PathName & "\Desktop\" & Sheet1.Cells(19, 2).Value  
 If FSO.FolderExists(FolderPath1) = False Then  
 MsgBox ("Folder not exist")  
 End If  
 If FSO.FolderExists(FolderPath1) = True Then  
 MsgBox ("Folder existed")  
 End If  
 End Sub  
==================================================


To download this example
Download example



No comments:

Post a Comment