VBA Code to Browse a Folder

Quite often a VBA developer requires code to browse a folder. This is mainly for saving the output file or reading the input file(s). Below is the VBA code that can be used to browse a file folder.

Excel Tricks

Public Sub PickAFolder()
    'Microsoft Office XX.X Object Library is required to run this code
    'Variable declaration
    Dim objFileDialog As FileDialog
    Dim objSelectedFolder As Variant
    'Browse a folder
    Set objFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    With objFileDialog
        .ButtonName = "Select"
        .Title = "Select a folder"
        .InitialView = msoFileDialogViewList
        For Each objSelectedFolder In .SelectedItems
            'Show the selected folder details on Excel sheet
            Sheet1.Range("B6").Value = objSelectedFolder
    End With
End Sub

It is worth to mention that you need to add Office reference (Microsoft Office XX.X Object Library) in Excel VBA from Menu Bar (Tools>References…). Below are the steps to add Office reference in Excel VBA:

1. From the Menu Bar, click on Tools > References…

Excel Tricks

2. Select ‘Microsoft Office XX.X Object Library’ and click on ‘OK’ button

Excel Tricks

To use this code in your Excel file, follow below steps:

1. Open an Excel file
2. Press Alt+F11
3. Insert a Module (Insert>Module) from menu bar
4. Paste the code in the module
5. Now add a shape in Excel sheet
6. Give a name to the shape like ‘Browse a Folder’

Excel Tricks

7. Right click on the shape and select ‘Assign Macro…’

Excel Tricks

8. Select PickAFolder from the list and click on ‘Ok’ button

Excel Tricks

9. Done

Leave a Reply

VBA Code to Sum Cells by Color
VBA Code to Sum Cells by Color

Recently some of our subscribers have requested us to share a VBA code that can sum the cells by its color. To help our subscribers and developers, we are sharing 2 codes that be used to sum the cells with specific color and returns the total sum of the matching color cells

VBA Tool to Track Start and End Time (Time & Motion Tracker)

Here is one more wonderful free tool from ExcelSirJi.com which makes your life easy. Time & Motion Tracker helps you to track Start and End time of any type of transaction or activity. The good thing is, it is VBA based tool which helps you to protect from manual manipulation in the data by the user. It is also easy to use, just click on Start (shortcut: Ctrl+Shift+A) or Stop (Ctrl+Shft+S) buttons to record the time

VBA Code to Delete File
VBA Code to Delete File

In this article we are going to show you how you can delete file or files using a single line of VBA code. 1. Delete a specific file from the folder, 2. Delete specific type of files from the folder, 3. Delete all files from the folder


Like the Article? Please spread the word :)