Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check is destination directory exist then proceed if not then create it and proceed afterwards

Tags:

excel

vba

I have a button on one of the worksheets that lets user to continue with his task to save his/her template as a separate workbook in the folder.

Here is my code

Private Sub ContinueButton_Click()
    Application.ScreenUpdating = 0
    Sheets(cmbSheet.Value).Visible = True
    Application.Goto Sheets(cmbSheet.Value).[a22], True
    Application.ScreenUpdating = 1
    Unload Me
End Sub

Now what I need is to check if that folder exist, in case if the folder does not exist my user should be able to create it.

My code to create this folder is here below, but how to connect this 2 functions together I simply have no idea, since I am fairly new to VBA

Sub CreateDirectory()
Dim sep As String
sep = Application.PathSeparator
'sets the workbook's path as the current directory
ChDir ThisWorkbook.Path
MsgBox "The current directory is:" & vbCrLf & CurDir
'makes new folder in current directory
MkDir CurDir & sep & Settings.Range("C45").Value
MsgBox "The archive directory named " & Settings.Range("C45").Value & " has been created. The path to your directory " & Settings.Range("C45").Value & " is below. " & vbCrLf & CurDir & sep & Settings.Range("C45").Value
End Sub
like image 450
AlexB Avatar asked Dec 25 '22 12:12

AlexB


1 Answers

I am going to modularize your code a little bit:

First get the directory path here

Function getDirectoryPath()
    getDirectoryPath = ThisWorkbook.Path & Application.PathSeparator & Settings.Range("C45").Value
End Function

You can create the directory using this function

Sub createDirectory(directoryPath)
    MkDir directoryPath
End Sub

You can check if a directory exists or not using Dir function

Dir(directoryPath, vbDirectory) 'empty string means directoryPath doesn't exist

The final function on button click:

Private Sub ContinueButton_Click()
    Application.ScreenUpdating = 0
    Sheets(cmbSheet.Value).Visible = True
    directoryPath = getDirectoryPath
    'Creating the directory only if it doesn't exist
    If Dir(directoryPath, vbDirectory) = "" Then
         createDirectory directoryPath
    End If
    Application.Goto Sheets(cmbSheet.Value).[a22], True
    Application.ScreenUpdating = 1
    Unload Me
End Sub
like image 195
AKS Avatar answered Feb 01 '23 11:02

AKS