You kinda have two questions here so lets start with the first. Here is some
code to look through folders and subfolders. Place this code in a standard
code module in a new workbook. (The code is compiled from a bunch of other
posts from Bob Phillips and others if I recall correctly but any errors would
undoubtedly be my own.)
Option Compare Text
Sub test()
Call ListFiles("H:\", Sheet2.Range("A2"), "xls", True)
End Sub
Public Sub ListFiles(ByVal strPath As String, _
ByVal rngDestination As Range, Optional ByVal strFileType As String = "*", _
Optional ByVal blnSubDirectories As Boolean = False)
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim strName As String
'Specify the file to look for...
strName = "*." & strFileType
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strPath)
For Each objFile In objFolder.Files
If objFile.Name Like strName Then
rngDestination.Value = objFile.Path
rngDestination.Offset(0, 1).Value = objFile.DateLastAccessed
Set rngDestination = rngDestination.Offset(1, 0)
End If
Next 'objFile
Set objFile = Nothing
'Call recursive function
If blnSubDirectories = True Then _
DoTheSubFolders objFolder.SubFolders, rngDestination, strName
Set objFSO = Nothing
Set objFolder = Nothing
End Sub
Function DoTheSubFolders(ByRef objFolders As Object, _
ByRef rng As Range, ByRef strTitle As String)
Dim scrFolder As Object
Dim scrFile As Object
Dim lngCnt As Long
On Error GoTo ErrorHandler
For Each scrFolder In objFolders
For Each scrFile In scrFolder.Files
If scrFile.Name Like strTitle Then
rng.Value = scrFile.Path
rng.Offset(0, 1).Value = scrFile.DateLastAccessed
Set rng = rng.Offset(1, 0)
End If
Next 'scrFile
'If there are more sub folders then go back and run function again.
If scrFolder.SubFolders.Count > 0 Then
DoTheSubFolders scrFolder.SubFolders, rng, strTitle
End If
ErrorHandler:
Next 'scrFolder
Set scrFile = Nothing
Set scrFolder = Nothing
End Function
Question 2 - How to interupt code... you can try something similar to this...
Dim lng As Long
Dim counter As Long
On Error GoTo ErrorHandler
Application.EnableCancelKey = xlErrorHandler
For lng = 1 To 100000000
counter = counter + 2
Next lng
ErrorHandler:
If Err = 18 Then
If MsgBox("Do you want to stop?", vbYesNo, "Quit?") = vbYes Then
MsgBox counter
Exit Sub
Else
Resume
End If
Else
MsgBox counter
End If