Canceling a read file function

  • Thread starter Thread starter mwc0914
  • Start date Start date
M

mwc0914

I have a macro where the user is required to select a file to open. This
is done via the Windows Open File dialog box. If they elect to "cancel"
and not open the file, I get an error. I know there must be some coding
I can put into my macro to trap this and just exit the macro if this
happens.

Thanks
Mike
 
hi Mike

Use GetOpenFilename

Sub test()
Dim FName As Variant
Dim wb As Workbook
Dim MyPath As String
Dim SaveDriveDir As String

SaveDriveDir = CurDir

MyPath = ThisWorkbook.Path
ChDrive MyPath
ChDir MyPath

FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xls), *.xls")
If FName <> False Then
Set wb = Workbooks.Open(FName)
MsgBox "your code"
wb.Close
End If

ChDrive SaveDriveDir
ChDir SaveDriveDir

End Sub
 
Application.GetOpenFilename, nice! I didn't know about that function. I was
surprised I didn't need to use quotes here:

If FName <> "False" Then


Ron de Bruin said:
hi Mike

Use GetOpenFilename

Sub test()
Dim FName As Variant
Dim wb As Workbook
Dim MyPath As String
Dim SaveDriveDir As String

SaveDriveDir = CurDir

MyPath = ThisWorkbook.Path
ChDrive MyPath
ChDir MyPath

FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xls), *.xls")
If FName <> False Then
Set wb = Workbooks.Open(FName)
MsgBox "your code"
wb.Close
End If

ChDrive SaveDriveDir
ChDir SaveDriveDir

End Sub
 
Back
Top