This method requires a reference to the Windows Script Host Object Model. To add select Tools and then References from the VBA menu. The references are listed alphabetically.
' Requires reference: Windows Script Host Object Model.
Sub FindFile()
Const ROOT_DIR As String = "C:\MI\Example" ' Update with your folder.
Dim fso As FileSystemObject ' Used to read from file system.
Dim fle As File ' Used to loop over files.
' Ready object variable for use.
Set fso = New FileSystemObject
' Loop over files.
For Each fle In fso.GetFolder(ROOT_DIR).Files
If fle.Name Like "*.docx" Then Application.Documents.Open fle.Name
Next
' Release object vars before they leave scope.
Set fso = Nothing
End Sub
The FileSystemObject is a powerful class, provided by Microsoft. It allows your code to interact with the Windows file system.
EDIT
The error user defined type not defined means the compiler does not recognise one your data types. In this case, it does not know what a FileSystemObject
is, so it cannot create the variable fso
of that type. To fix it needs the reference, mentioned above. This contains the definition, telling VBA what an fso is, and how it works.
From the menu strip can you click Tools >> References and double check Windows Script Host Object Model is checked (selected references should be at the top, the rest are listed alphabetically).
