0

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?

5
  • 1
    Does it help: sFound = Dir(fPath & "\Advanced Risk Management Report*.xlsx"). Path and filename must be separated. Also when Open Commented Jan 20 at 11:29
  • The problem is that ThisWorkbook.Path returns an empty string (at least on my copy). I changed the Dir match to "*.xlsx" which meant that it did find some .xlsx files on my machine but since Workbooks.Open requires a fully qualified long filename and because fPath is empty it then fails Runtime Error '1004' . Commented Jan 20 at 11:48
  • 1
    ThisWorkbook.Path returns an empty string if the workbook is not yet saved. Commented Jan 20 at 11:49
  • check this line too Set WB1 = Workbooks.Open(fPath & Found) Commented Jan 20 at 11:50
  • 1
    I'm guessing you haven't got Option Explicit at the top of your module - you search for sFound and try and open Found. Without Option Explicit the code will just happily create a variant variable called Found and assign it an empty string. You also don't put the path separator in the Dir call so fPath is .....\My Documents rather than `...\My Documents\`. Commented Jan 20 at 14:05

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.