arnelgp
..forever waiting... waiting for jellybean!
- Local time
- Today, 09:35
- Joined
- May 7, 2009
- Messages
- 19,881
here is the code.
run sub Test (it will only display the filename).
i included the function that test If the file is open (you need to call it on each collection.item)
run sub Test (it will only display the filename).
i included the function that test If the file is open (you need to call it on each collection.item)
Code:
Public Sub RecursiveDir(ByRef colFiles As Collection, _
ByVal strFolder As String, _
ByVal strFileSpec As String, _
Optional ByVal bIncludeSubfolders As Boolean = False)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
On Error Resume Next
'Add files in strFolder matching strFileSpec to colFiles
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
'Fill colFolders with list of subdirectories of strFolder
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Sub
Private Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
' https://exceloffthegrid.com/vba-find-file-already-open/
Function IsFileOpen(fileName As String)
Dim fileNum As Integer
Dim errNum As Integer
'Allow all errors to happen
On Error Resume Next
fileNum = FreeFile()
'Try to open and close the file for input.
'Errors mean the file is already open
Open fileName For Input Lock Read As #fileNum
Close fileNum
'Get the error number
errNum = Err
'Do not allow errors to happen
On Error GoTo 0
'Check the Error Number
Select Case errNum
'errNum = 0 means no errors, therefore file closed
Case 0
IsFileOpen = False
'errNum = 70 means the file is already open
Case 70
IsFileOpen = True
'Something else went wrong
Case Else
IsFileOpen = errNum
End Select
End Function
Private Sub TEST()
Dim c As New Collection
Dim i As Long
Call RecursiveDir(c, "d:\", "*.*", True)
For i = 1 To c.count
Debug.Print c(i)
Next
End Sub