Detecting user cancel out of "File Open" input box

V

vrzimmerm

The following macro segment is supposed to detect if the user
cancelled out of an "Open File" input window, but I keep getting a
"subscript out of range" error. What am I doing wrong?

Dim FName As Variant
FName = Application.GetOpenFilename("Excel Files (*.xls),*.xls")
If Not FName = False Then Workbooks.Open FName
Application.DisplayAlerts = False

If FName <> False Then
Set wb = Workbooks.Open(FName)
MsgBox "File open cancelled"
wb.Close
End If

Thanks.
 
J

JW

Your code works fine for me. It opens the file that the user selects,
shows a message box stating that "file open canceled", and then closes
the workbook that it opened. Don't see what that is accomplishing,
but it did what you want according to your code.
Word of advice, although Excel is supposed to turn DisplayAlerts back
on once a procedure is complete, I still recommend getting in the
habit of turning them back on in your code.
Application.DisplayAlerts = True
 
V

vrzimmerm

The following macro segment is supposed to detect if the user
cancelled out of an "Open File" input window, but I keep getting a
"subscript out of range" error. What am I doing wrong?

Dim FName As Variant
FName = Application.GetOpenFilename("Excel Files (*.xls),*.xls")
If Not FName = False Then Workbooks.Open FName
Application.DisplayAlerts = False

If FName <> False Then
Set wb = Workbooks.Open(FName)
MsgBox "File open cancelled"
wb.Close
End If

Thanks.

For some reason it's not recognizing that the user canceled out of the
"open file" window as the message box isn't even being displayed.
The error is found in a spot lower down in my code (where it has
assumed that a file had been opened.) When the user cancels out
all I want is for the "Open file" window to close and then the user
should be brought back to the file where the macro resides.
 
J

JW

Sub fOpenTest()
Dim FName As Variant
FName = Application.GetOpenFilename("Excel Files (*.xls),*.xls")
If FName = False Or FName = "" Then Exit Sub
'Rest of your code here
End Sub
 

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