Tested in Excel 365 (16.8730.2046) 64-bit
- Public Function GetFileNameOrPath(FilePath As String, Optional FileOrFolder As String = "File") As String
- ' FileOrFolder should be: file, folder or missing
- ' default return is file name
- Dim FolderPath As String, FileName As String
- FolderPath = Left(FilePath, InStrRev(FilePath, "\") - 1)
- FileName = Right(FilePath, Len(FilePath) - Len(FolderPath) - 1)
- If UCase(FileOrFolder) = "FILE" Then
- GetFileNameOrPath = FileName
- Else
- GetFileNameOrPath = FolderPath
- End If
- End Function
- ' use it like this:
- Sub main()
- Dim myPath As String
- myPath = GetFileNameOrPath("C:\datafile.csv", "folder")
- Debug.Print myPath
- End Sub