Я бы вообще не использовал диалог FileOpen.Рассмотрим FilePicker: пользователь выбирает файл, а затем вы решаете, хотите ли вы открыть его.Вот код для игры.
Private Sub TestFileOpenName()
Dim Fn As String
Dim Sp() As String
' the Flt argument = 1 which results in Word documents being filtered
Fn = FileOpenName("Select a file", 1, "C:\My Dopcuments\")
' the Flt argument = "Word documents|*.doc*" which also results in
' Word documents being filtered (modify filter as required)
' Fn = FileOpenName("Select a file", "Word documents|*.doc*", "D:\My Dopcuments\")
' the Flt argument = 1 or 2 which results in Word documents being filtered
' but type drop-down allows changing to Excel.
' Specify "2||1" to make Excel the default and Word the alternative
' Fn = FileOpenName("Select a file", "1||2", "C:\My Dopcuments\")
If Len(Fn) Then
MsgBox "The selected file is" & vbCr & Fn
Sp = Split(Fn, ".")
If InStr(1, Sp(UBound(Sp)), "doc", vbTextCompare) = 1 Then
MsgBox "I will now open the document"
Else
MsgBox "Please select a Word document." & vbCr & _
"Sorry, I can't proceed."
End If
Else
MsgBox "No file was selected"
End If
End Sub
Function FileOpenName(ByVal Title As String, _
Optional ByVal Flt As Variant = 0, _
Optional ByVal Pn As String) As String
' SSY 050 ++ 14 Dec 2018
' ==================================================
' Parameters:
' Title = Form's title
' Flt = Specify filters by ID or string specs
' separated by || (= 2 x Chr(124))
' in sequence of position assignment.
' Default = no filter [=All files]
' Pn = Initial path: [=Last used]
' ==================================================
' Note: The ButtonName is "Open" by default. Another setting
' doesn't take effect until a file has been selected.
' ==================================================
Const FltDesc As Long = 0, FltExt As Long = 1
Dim Fod As FileDialog ' File Open Dialog
Dim Fts() As String ' all filters
Dim Sp() As String ' split filter
Dim i As Long
' ==================================================
Fts = Split(Flt, "||")
ReDim Sp(3)
Sp(1) = "Word documents|*.doc*"
Sp(2) = "Excel workbooks|*.xls*"
Sp(3) = "Image file|*.png, *.tif"
For i = 0 To UBound(Fts)
If IsNumeric(Fts(i)) Then Fts(i) = Sp(Fts(i))
Next i
Set Fod = Application.FileDialog(msoFileDialogFilePicker)
With Fod
.Filters.Clear
For i = 0 To UBound(Fts)
If Len(Fts(i)) Then
Sp = Split(Fts(i), "|")
.Filters.Add Sp(FltDesc), Sp(FltExt), i + 1
.FilterIndex = 1
End If
Next i
.Title = Title
.AllowMultiSelect = False
.InitialFileName = Pn
If .Show Then FileOpenName = .SelectedItems(1)
End With
End Function