Prompt user to select file

0
142

The following module is an interface which prompts the user of the document to select a text file from a pop up dialog box (similar to the Open or Save As window). Once the file is selected, the pathname and document name is recorded. This pathname/filename can then be used to automatically open the text file and further coding used to import and format the data. This macro is particularly useful for reporting purposes where data is imported on a regular basis.

Select a File

Step 1

Open a workbook and start the Visual Basic Editor (Alt + F11). Right Click in the project explorer windown and select Insert > Module. Copy the following code into the new Module and then select Run to test the macro.

Option Explicit
Sub FileName()

Dim FileType
Dim Title As String
Dim FileName

FileType = "Text Files (*.txt),*.txt,"
Title = "Please select this file:"

FileName = Application.GetOpenFilename(FileFilter:=FileType, Title:=Title)

If FileName = False Then
MsgBox "No file selected.", vbOKOnly, "Error"
Else
MsgBox "Path and File selected is: " & FileName
End If

End Sub

If you have a question on this post for the Excel Help Desk team or have something you would like to share on this topic then please leave a comment.