Home » excel » excel – Checking if file extension is .xlsx before adding in array

excel – Checking if file extension is .xlsx before adding in array

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m created a loop for me to get the files in a specific folder but I’m wondering how can I make sure that the filenames that will be added in the myArray will only contain .xlsx or .xls?

Function listFiles(ByVal get_Path As String)

Dim myArray As Variant
Dim i As Integer
Dim counter As Integer
Dim xFile As Object
Dim FileServ As Object
Dim the_Folder As Object
Dim the_Files As Object

Set FileServ = CreateObject("Scripting.FileSystemObject")
Set the_Folder = FileServ.GetFolder(get_Path)
Set the_Files = the_Folder.Files

    'Check if folder is empty
    If the_Files.Count = 0 Then
        Exit Function
    End If

    'Declare the size of Array based on the number of Files inside the folder
    ReDim myArray(1 To the_Files.Count)

    'Loop through each file and assign each filename in Array
    i = 1
    For Each xFile In the_Files
        myArray(i) = xFile.Name
        i = i + 1
    Next


    listFiles = myArray

End Function
How to&Answers:

You can do this:

i = 0
For Each xFile In the_Files
    If xFile.Name Like "*.xls" or xFile.Name Like "*.xlsx" Then
        i = i + 1
        myArray(i) = xFile.Name
    End If
Next

Redim Preserve myArray(1 to i)