Monday, January 4, 2016

How to Get Extension File in VBA

Check "xlsx" extension file. Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Sub Button1_Click()

Dim Target As String, pos As Long
Target = Application.GetOpenFilename()
pos = InStrRev(Target, ".")
If pos > 0 Then
    If LCase(Mid(Target, pos + 1)) = "xlsx" Then
        ' process for target file
        MsgBox "This xlsx extension file"
    Else
        MsgBox "Not xlsx Extension file", 48
    End If
End If

End Sub

Check "xlsx" or "xls"  extension file. Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Sub Button2_Click()

Dim Target As String, pos As Long
Target = Application.GetOpenFilename()
pos = InStrRev(Target, ".")
If pos > 0 Then
    If LCase(Mid(Target, pos + 1)) = "xls" Or _
       LCase(Mid(Target, pos + 1)) = "xlsx" Then
        ' process for target file
        MsgBox "This xlsx extension file"
    Else
        MsgBox "Not xlsx Extension file", 48
    End If
End If

End Sub

or , can do with

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Sub Button3_Click()

Dim Target As String, pos As Long
Target = Application.GetOpenFilename()
pos = InStrRev(Target, ".")
If pos > 0 Then
    If LCase(Mid(Target, pos + 1)) Like "xls*" Then
        ' process for target file
        MsgBox "This xlsx extension file"
    Else
        MsgBox "Not xlsx Extension file", 48
    End If
End If

End Sub

With use FileSystemObject

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Sub Button4_Click()
    Dim Target As String
    Target = Application.GetOpenFilename()
    With CreateObject("Scripting.FileSystemObject")
        If LCase(.GetExtensionName(Target)) = "xls" Or _
           LCase(.GetExtensionName(Target)) = "xlsx" Then
            ' process for target file
            MsgBox "This xlsx extension file"
        Else
            MsgBox "Not xlsx Extension file", 48
        End If
    End With
End Sub


Downloan File



No comments :

Post a Comment