vbaget

Get file extension vba


i need to store the extension from files in a variable in VBA, What i've done for now is

file= Hello.pdf
extension = split(file,".")(1)

But sometimes my file could be like file = 1.Filename.pdf and so my extension variable is not working anymore...

could someone help me to find a solution to always get the extension from any file name even if they are multiples "." in it.

i had an idea it waas to read from right to left and get the string when it read a "." but i'm new in vba and don't know where to look to start it....


Solution

  • Try,

    Dim vFn As Variant
    
    file = "Hello.pdf"
    
    vFn = Split(file, ".")
    extension = vFn(UBound(vFn))
    

    OR

    Function FileExt(Optional str = "1.2.3.4.5.dd")
        FileExt= Right(str, Len(str) - InStrRev(str, "\"))
    End Function