Option Explicit
Sub OpenRecentFileReadOnlyNew()
Dim RecentFilesList As String
Dim SelectedIndex As Variant
Dim FilePath As String
Dim FileName As String
Dim i As Integer
Dim TotalFiles As Integer
Dim ValidFiles As Collection
Dim FileCount As Integer
Set ValidFiles = New Collection
TotalFiles = Application.RecentFiles.Count
If TotalFiles = 0 Then
MsgBox "No recent files available.", vbExclamation
Exit Sub
End If
For i = 1 To TotalFiles
If Len(Application.RecentFiles(i).Name) > 0 Then
On Error Resume Next
FileName = Dir(Application.RecentFiles(i).Name)
If Len(FileName) > 0 Then
ValidFiles.Add Application.RecentFiles(i).Name
End If
On Error GoTo 0
End If
Next i
If ValidFiles.Count = 0 Then
MsgBox "No valid recent files available.", vbExclamation
Exit Sub
End If
RecentFilesList = "Select a file to open as read-only:" & vbCrLf
For i = 1 To ValidFiles.Count
FileName = Dir(ValidFiles(i))
RecentFilesList = RecentFilesList & i & ". " & FileName & vbCrLf
Next i
SelectedIndex = InputBox(RecentFilesList, "Open Recent File Read-Only")
If SelectedIndex = "" Then
Exit Sub
End If
On Error Resume Next
FilePath = ValidFiles(CInt(SelectedIndex))
If Err.Number <> 0 Or FilePath = "" Then
MsgBox "Invalid selection. Please choose a valid file number.", vbExclamation
Err.Clear
On Error GoTo 0
Exit Sub
End If
Workbooks.Open FilePath, ReadOnly:=True
If Err.Number <> 0 Then
MsgBox "Unable to open the file. It may have been moved or deleted.", vbExclamation
Err.Clear
End If
On Error GoTo 0
End Sub