For Each ObjFile In objFolder.Files help

GODZILLA

Registered User.
Local time
Yesterday, 16:46
Joined
Mar 15, 2010
Messages
70
Hello,

I currently have this bit of code For Each ObjFile In objFolder.Files, which is looking at each file with in a specfic folder.

What im now looking to do is have it look at every file within a folder with in an other folder or directory.

Can anyone pont me in the right direction.

Thanks

Code:
Dim ObjFSO As FileSystemObject
Dim objFolder As Folder
Dim ObjFile As File

Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = ObjFSO.GetFolder(strpath)

For Each ObjFile In objFolder.Files
 
I have a form and use a list box, when the form is opened it will show all files in the list box, starting at a folder level but then showing all files within sub folders.

If I want to open any file I have also added additional code to open on double clicking the file name in the list box.

Here is an extract, note it has a const at the top which is the start point to look in.

Const strdirpath = "M:\Access Files"
Private Sub Form_Load()
Dim strfile As String
ChDir strdirpath
strfile = Dir("*.*")
Do Until strfile = ""
Me.lstfiles.AddItem strfile
strfile = Dir
Loop


End Sub
Private Sub lstfiles_Click()
Dim app As Object

Select Case LCase(Right(Me.lstfiles.Value, 3))
Case "xls"
Set app = CreateObject("Excel.Application")
app.Visible = True
app.workbooks.Open strdirpath & "\" & Me.lstfiles.Value
Case "doc"
Set app = CreateObject("Word.Application")
app.Visible = True
app.Documents.Open strdirpath & "\" & Me.lstfiles.Value
Case "txt"
Set app = CreateObject("Word.Application")
app.Visible = True
app.Documents.Open
Case "htm"
Set app = CreateObject("Word.Application")
app.Visible = True
app.Documents.Open
Case Else
MsgBox "Cannot open this file type"
End Select

Set app = Nothing

End Sub
 
In respect to the loop you posted about, the folder the code looks in is determined at this line ...
Code:
Set objFolder = ObjFSO.GetFolder([COLOR="DarkRed"]strPath[/COLOR])
To change the folder the code loops through, change the value of strPath and rerun the routine.
By way of example, consider this Sub, which allows you to pass in the path ...
Code:
Sub IterateThruFilesInFolder([COLOR="DarkRed"]strPath[/COLOR] as string)
  Dim fso As New FileSystemObject  [COLOR="Green"]'created using the New keyword[/COLOR]
  Dim fd As Folder
  Dim f As File

  Set fd = fso.GetFolder([COLOR="DarkRed"]strPath[/COLOR])  [COLOR="Green"]'create folder object[/COLOR]

  For Each f In fd.Files  [COLOR="Green"]'traverse files in fd[/COLOR]
    'do something with each f
  next
End Sub
 

Users who are viewing this thread

Back
Top Bottom