excelvbafilenamesgetopenfilename

How do you get just the filename rather than the entire file path of an open file?


In other words, would I need to do some string processing after invoking the Application.GetOpenFileName() Method?


Solution

  • I am using these functions for filename processing. The last one is the one you need here.

    Public Function FilePathOf(ByVal s As String) As String
        Dim pos As Integer
    
        pos = InStrRev(s, "\")
        If pos = 0 Then
            FilePathOf = ""
        Else
            FilePathOf = Left$(s, pos)
        End If
    End Function
    
    Public Function FileNameOf(ByVal s As String) As String
        Dim pos1 As Integer, pos2 As Integer
    
        pos1 = InStrRev(s, "\") + 1
        pos2 = InStrRev(s, ".")
        If pos2 = Len(s) Then pos2 = pos2 + 1
        If pos2 = 0 Then pos2 = Len(s) + 1
        FileNameOf = Mid$(s, pos1, pos2 - pos1)
    End Function
    
    Public Function FileExtOf(ByVal s As String) As String
        Dim pos As Integer
    
        pos = InStrRev(s, ".")
        If pos = 0 Then
            FileExtOf = ""
        Else
            FileExtOf = Mid$(s, pos + 1)
        End If
    End Function
    
    Public Function FileNameExtOf(ByVal s As String) As String
        FileNameExtOf = Mid$(s, InStrRev(s, "\") + 1)
    End Function