Home » excel » vba – Prompt User to Select a File Path on Cell Selection in Excel

vba – Prompt User to Select a File Path on Cell Selection in Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a worksheet that downloads a bunch of files to a location specified by a user in a cell . What I’d like to do is add validation to this cell such that when it is clicked, the file selection window opens, and the user is able to specify the desired location. Is this even possible? I know it can be done through a button triggered macro, but I’d really like it to work more like other types of validation, such as a drop down menu.

Any pointing in the right direction would be much appreciated…non computer types have more trouble typing in error free paths than you could possibly believe.

How to&Answers:

Stick this in the Workbook object. Alternatively, if it is a specific sheet, then stick it in the sheet object and change the event to relevant worksheet one – this will save a few CPU cycles as it will only fire the event on the relevant worksheet.

Public SelectedPath As String
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    Dim desiredCell As Range
    Set desiredCell = Worksheets("Sheet1").Cells(1, 1) 'whatever
    If Target.Address(external:=True) = desiredCell.Address(external:=True) Then
        With Application.FileDialog(msoFileDialogFolderPicker)
            .AllowMultiSelect = False
            .ButtonName = "Select destination"
            .Title = "Select destination folder"
            .Show
            If .SelectedItems.Count > 0 Then
                SelectedPath = .SelectedItems(1)
                Target.Value = SelectedPath
            End If
        End With
        'do some more stuff or let your other code access the SelectedPath field
    End If
End Sub