Search code examples
excelvba

VBA Excel Cannot open external workbook


I found a nice, although incomplete, solution here: Excel VBA open workbook with part of its name

and formulated the code based on my example

Option Explicit

Sub NewWorksheet()

Dim sFound As String, fPath As String
Dim WB1 As Workbook

fPath = ThisWorkbook.Path
sFound = Dir(fPath & "Advanced Risk Management Report*.xlsx")
If sFound <> "" Then
Set WB1 = Workbooks.Open(fPath & Found)
End If


End Sub

Unfortunately, the code doesn't work. There is no error either. What could be missing here?


Solution

  • First select Tools > Options and tick Require Variable Declaration.
    In all new modules going forward you'll get Option Explicit at the top of the module.

    enter image description here

    Now just update your code as below:

    Option Explicit
    
    Sub NewWorksheet()
    
        Dim sFound As String, fPath As String
        Dim WB1 As Workbook
        
        fPath = ThisWorkbook.Path & "\" 'Added & "\"
        sFound = Dir(fPath & "Advanced Risk Management Report*.xlsx")
        If sFound <> "" Then
            Set WB1 = Workbooks.Open(fPath & sFound) 'Updated Found to sFound.
        End If
    
    End Sub