Home » excel » excel – Open only .xls files in a given directory using macro

excel – Open only .xls files in a given directory using macro

Posted by: admin May 14, 2020 Leave a comment

Questions:

Just wondering… I have a piece of code – a macro in excel that allows me to open files in a given directory. The thing is that I only want to open .xls files, and the code that I have opens all the files in a given directory.

Can anyone help me with this matter.

Thanks.

Sub FindOpenFiles()
Dim FSO As Scripting.FileSystemObject, folder As Scripting.folder, file As Scripting.file, wb As Workbook
Dim directory As String

    directory = "O:\test"

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder = FSO.GetFolder(directory)

    For Each file In folder.Files
        Workbooks.Open file
    Next file
End Sub
How to&Answers:
Sub FindOpenFiles()
Dim FSO As Scripting.FileSystemObject, folder As Scripting.folder, file As Scripting.file, wb As Workbook
Dim directory As String

    directory = "O:\test"

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder = FSO.GetFolder(directory)


    For Each file In folder.Files
        If Mid(file.Name, InStrRev(file.Name, ".") + 1) = "xls" Then
            Workbooks.Open directory & Application.PathSeparator & file.Name
        End If
    Next file
End Sub

This woks fine…

Answer:

See if this works, may need a tweak or two!

For Each file In folder.Files
    If Right(file, 4) = ".xls" Then
        Workbooks.Open file
    End If
Next file

Answer:

Try this but I am not really sure

directory = “*.xls”