Pick a file or a folder using a dialog

 
 
  1. Public Function PickFileOrFolder(Optional IsFile = True, Optional MultiFile = False, Optional DialogTitle = "Please select...") As String
  2. '===================================================================================
  3. ' Created by: Sanda Vladescu
  4. ' Updated on:
  5. ' Purpose:
  6. ' References: Microsoft ActiveX Data object...
  7. ' Usage example:
  8. ' arrFile=split(PickFileOrFolder(1,1),"|")
  9. '===================================================================================
  10.     Dim FileOrFolder
  11.     Dim BrowserFolder, MyPath As String, item, itemNb
  12.    
  13.     If IsFile Then
  14.         FileOrFolder = msoFileDialogFilePicker
  15.     Else
  16.         FileOrFolder = msoFileDialogFolderPicker
  17.     End If
  18.    
  19.     Set BrowserFolder = Application.FileDialog(FileOrFolder)
  20.     With BrowserFolder
  21.         .AllowMultiSelect = MultiFile
  22.         .InitialFileName = Application.DefaultFilePath
  23.         .Title = DialogTitle
  24.         .Show
  25.         If MultiFile Then
  26.             itemNb = 0
  27.             For Each item In Application.FileDialog(FileOrFolder).SelectedItems
  28.                 itemNb = itemNb + 1
  29.                 MyPath = MyPath & Application.FileDialog(FileOrFolder).SelectedItems(itemNb) & "|"
  30.             Next item
  31.         Else
  32.         MyPath = Application.FileDialog(FileOrFolder).SelectedItems(1)
  33.         End If
  34.     End With
  35.    
  36.     PickFileOrFolder = MyPath
  37. End Function

Then, you can use this to get the file name or the path.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.