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
' Initialize a collection to hold valid file paths
Set ValidFiles = New Collection
' Get the total number of recent files Excel tracks
TotalFiles = Application.RecentFiles.Count
' Check if there are any recent files
If TotalFiles = 0 Then
MsgBox "No recent files available.", vbExclamation
Exit Sub
End If
' Create a list of valid recent file names (excluding paths)
For i = 1 To TotalFiles
' Check if the file path is valid and not empty
If Len(Application.RecentFiles(i).Name) > 0 Then
On Error Resume Next
' Try to get the file name using Dir (check for valid file)
FileName = Dir(Application.RecentFiles(i).Name)
If Len(FileName) > 0 Then
' Add the valid file to the collection
ValidFiles.Add Application.RecentFiles(i).Name
End If
On Error GoTo 0
End If
Next i
' If no valid recent files, show a message and exit
If ValidFiles.Count = 0 Then
MsgBox "No valid recent files available.", vbExclamation
Exit Sub
End If
' Build the prompt list for the InputBox
RecentFilesList = "Select a file to open as read-only:" & vbCrLf
For i = 1 To ValidFiles.Count
FileName = Dir(ValidFiles(i)) ' Get the file name with extension
RecentFilesList = RecentFilesList & i & ". " & FileName & vbCrLf
Next i
' Use InputBox to get the user's choice
SelectedIndex = InputBox(RecentFilesList, "Open Recent File Read-Only")
' Exit if the user cancels or provides no input
If SelectedIndex = "" Then
Exit Sub
End If
' Convert the selection to a number and attempt to open the file
On Error Resume Next
FilePath = ValidFiles(CInt(SelectedIndex)) ' Get the valid file path
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
' Open the file in read-only mode
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