VBA ChDir Function

VBA ChDir Function in Excel

VBA ChDir function in Excel is categorized as File and Directory function. This built-in VBA ChDir statement changes the current or default folder or directory in Excel.

This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA ChDir Function in any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the ChDir function, where we can use this ChDir Function and real-time examples in Excel VBA.

Syntax of VBA ChDir Function

The syntax of the ChDir Function in VBA is

ChDir(Path)

Note: The ChDir Function changes the current directory or folder name .

Parameters or Arguments:

The ChDIr function/statement has one argument in Excel VBA.
where
Path: It is a mandatory string type parameter. The path argument represents the folder or directory that you want to change.

Where we can apply or use VBA ChDir Function?

We can use this ChDir Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Change Current Directory

Here is a simple example of the VBA ChDir function. This below example changes the current directory to “C:\Temp”.

'Change Current Directory
Sub VBA_ChDir_Function_Ex1()
    
    'Variable declaration
    Dim sDirectory As String
    
    sDirectory = "C:\Temp"
      
    ChDir sDirectory
   
    'Display output message
    MsgBox "Current Directory is : " & sDirectory, vbInformation, "VBA ChDir Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA ChDir Function

Example 2: Change Current Folder

Here is a simple example of the VBA ChDir function. This below example sets the current folder to “C:\Temp\VBAF1”.

'Change Current Folder
Sub VBA_ChDir_Function_Ex2()
    
    'Variable declaration
    Dim sDirectory As String
    
    sDirectory = "C:\Temp\VBAF1"
      
    ChDir sDirectory
   
    'Display output message
    MsgBox "Current Folder is : " & sDirectory, vbInformation, "VBA ChDir Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA ChDir Function

Example 3: Moves up one directory

You can find below statement to Moves up one directory. Here we use two periods(dots) to make relative directory changes.

ChDir ".."

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Leave a Reply