Get file extension


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'**********************************************************************************************************
' Name:         getFileExtension
' Author:       mielk | 2012-03-26
'
' Comment:      Function returns the file extension from a given filepath.
'
' Parameters:
'   filepath    The path of a file which extension is to be returned.
'
' Returns:
'   String      The extension of a given file.
'               If the given parameter is not a proper file path, an empty String is returned.
'
'
' --- Changes log -----------------------------------------------------------------------------------------
' 2012-03-26        mielk           Function created.
'**********************************************************************************************************
Public Function getFileExtension(filepath As String) As String
    Const METHOD_NAME As String = "getFileExtension"
    Const DOT As String = "."
    Const SLASH As String = "\"
    '------------------------------------------------------------------------------------------------------
    Dim lastDot As Integer
    Dim lastSlash As Integer
    '------------------------------------------------------------------------------------------------------

    'Find the position of last dot (.) and last slash (\) in the given filepath.
    lastDot = VBA.InStrRev(filepath, DOT)
    lastSlash = VBA.InStrRev(filepath, SLASH)

    'The given filepath is the proper path only if at least one dot was found and it is placed ----------|
    'after last slash. Otherwise empty String will be returned.                                         '|
    If lastDot Then                                                                                     '|
                                                                                                        '|
        '----------------------------------------------------------------------------------------|      '|
        If lastDot > lastSlash Then                                                             '|      '|
            getFileExtension = VBA.Mid$(filepath, lastDot + 1)                                  '|      '|
        End If                                                                                  '|      '|
        '----------------------------------------------------------------------------------------|      '|
                                                                                                        '|
    End If                                                                                              '|
    '----------------------------------------------------------------------------------------------------|


End Function