Home » excel » excel – Open workbooks in current directory

excel – Open workbooks in current directory

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a master workbook which includes a list of files (E14:E26), some of which are blank (empty) cells. I need code to loop through the list and open the workbooks listed (all of which are in the current directory). I’ve tried this code but get error messages:

Sub SkipBlankCells()
    Dim cell As Range, rng As Range, FName As String

    Set rng = Range("E14:E26")

    For Each cell In rng
        If Not IsEmpty(cell) Then
            FName = cell.Value
            Workbooks.Open Filename:=FName
        End If
    Next cell
End Sub
How to&Answers:

I suppose the cells don’t contain the whole path to the workbooks, just the filenames so this should work:

    Sub SkipBlankCells()
        Dim cell As Range, rng As Range, FName As String

        Set rng = Range("E14:E26")

        For Each cell In rng
            If Not IsEmpty(cell) Then
                FName = vbNullString
                FName = Dir(thisworkbook.Path & "\" & cell.Value) 'use dir to get the filename. If it doesn't exists, it will return blank
                If Not FName = vbNullString then Workbooks.Open _
                   Filename:=Thisworkbook.Path & "\" & FName 'to open a workbook you need the whole path to it, not only the file name.
            End If
        Next cell
    End Sub

Answer:

This function should work. I think that the problem of your function was the path. To solve that I used the function ActiveWorkbook.Path but just for you to know, you can use a literal path for example "C:\Users\bor\Documents\folder_with_files" to use a different path.

Sub open_file_list()
    first_row = 14 'in your case
    last_row = 26 'in your case
    For i = first_row To last_row
        If Not IsEmpty(Cells(i, 5)) Then 'Check for empty
            file = Cells(i, 5)
            Workbooks.Open (ActiveWorkbook.Path & "\" & file)
            End If
    Next

End Sub