GetOpenFilename - Trapping Errors

T

Tim Childs

Hi

I used the VB Example code from Microsoft Help but wanted to select MULTIPLE
files and have Option Explicit declared. The error trapping no longer worked
properly for no file being selected n the dialog box- can someone give me a
hand in getting it to work.

Thanks

Tim

Option Explicit
Sub ImportBudgetFileData()

Dim FileToOpen

FileToOpen = Application _
.GetOpenFilename("Text Files (*.xls), *.xls", , , , True)
'If FileToOpen(1) <> False Then
' MsgBox "Open " & FileToOpen
'End If
 
G

Guest

Hi Tim,

The example code in VBA Help doesn't work if MultiSelect is set to true.
Setting MultiSelect to TRUE results in VBA expecting an array, even if it's
only a single selection. You may want to consider the following code (by John
Walkenbach) if you intent to work with an array of filenames:

Sub GetImportFileName2()
Dim Filt As String
Dim FilterIndex As Integer
Dim FileName As String
Dim Title As String
Dim i As Integer
Dim Msg As String

' Set up list of file filters
Filt = "Text Files (*.txt),*.txt," & _
"Lotus Files (*.prn),*.prn," & _
"Comma Separated Files (*.csv),*.csv," & _
"ASCII Files ((*.asc),*.asc," & _
"All Files (*.*),*.*"

' Display *.* by default
FilterIndex = 5

' Set the dialog box caption
Title = "Select a file to import"

' Get the filename
FileName = Application.GetOpenFilename _
(FileFilter:=Filt, _
FilterIndex:=FilterIndex, _
Title:=Title, _
MultiSelect:=True)

' Exit if dialog box canceled
If Not IsArray(FileName) Then
MsgBox "No file was selected."
Exit Sub
End If

' Display full path and name of the files
For i = LBound(FileName) To UBound(FileName)
Msg = Msg & FileName(i) & vbCrLf
Next i
MsgBox "You selected:" & vbCrLf & Msg
End Sub

HTH
Regards,
GS
 
G

Guest

A mistake exists in the declarations. The correction:

Dim FileName As String

should be:

Dim FileName As Variant

Regards,
GS
 
T

Tim Childs

Hi

Many thanks for this response - I found the help on filters useful, too

bw

Tim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top