Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, and Excel in Office 365. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Getting a File Name.
by Allen Wyatt
(last updated January 3, 2020)
If you are writing a VBA macro in Excel, you may have a need to allow the user to specify a file they want from the disk. Fortunately, you can access the standard Open dialog box from within VBA and use it to return just a file name. The following example subroutine shows how this is done:
Sub GetFName() Dim FName As Variant Dim Msg As String FName = Application.GetOpenFilename() If FName <> False Then Msg = "You chose " & FName MsgBox Msg Else 'Cancel was pressed End If End Sub
When you run this macro, you will see the standard Open dialog box used in Excel. The user can select a file, and when they click on Open, the file name (including the full path) is assigned to the variable FName. If the user clicks on the Cancel button, then FName is set equal to False. (Thus the test for that in the code.)
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (11635) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Office 365. You can find a version of this tip for the older menu interface of Excel here: Getting a File Name.
Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!
If you need to exit a macro before it is finished running, you can do it using a brute force method, or you can build in ...Discover More
Named ranges are a great capability provided by Excel. You can define all sorts of named ranges in a workbook, but how do ...Discover More
Using a macro to add worksheets to your workbook is easy. This tip provides two different methods you can use.Discover More
Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.