Vba word application getopenfilename

Содержание

  • 1 Application.GetOpenFilename
  • 2 Get the selected file name in a file open dialog
  • 3 Load excel file
  • 4 Selecting multiple files
  • 5 Use filter in Open file dialog

Application.GetOpenFilename

   <source lang="vb">

Sub ManyFiles()

   Dim x As Variant
   x = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*",Title:="Choose Files", MultiSelect:=True)
   
   On Error Resume Next
   If x = "False" Then Exit Sub
   On Error GoTo 0
   
   For i = 1 To UBound(x)
       MsgBox "You selected " & x(i)
   Next i

End Sub

</source>
   
  

Get the selected file name in a file open dialog

   <source lang="vb">

Sub GetImportFileName()

   Filt = "Text Files (*.txt),*.txt," & _
          "Lotus Files (*.prn),*.prn," & _
          "Comma Separated Files (*.csv),*.csv," & _
          "ASCII Files (*.asc),*.asc," & _
          "All Files (*.*),*.*"
   FilterIndex = 5
   Filename = Application.GetOpenFilename (FileFilter:=Filt, FilterIndex:=FilterIndex, Title:="Select a File to Import")
   If Filename = False Then
       MsgBox "No file was selected."
       Exit Sub
   End If
   Debug.Print Filename

End Sub

</source>
   
  

Load excel file

   <source lang="vb">

Sub LoadExcelFile()

 Dim result
 result = Application.GetOpenFilename("Excel files,*.xl?", 1)
 If result = False Then Exit Sub
 Workbooks.Open result

End Sub

</source>
   
  

Selecting multiple files

   <source lang="vb">

 Sub GetImportFileName2()
     Dim FileNames As Variant
     Dim Msg As String
     Dim I As Integer
     FileNames = Application.GetOpenFilename(MultiSelect:=True)
     If IsArray(FileNames) Then
         Msg = "You selected:" & vbNewLine
         For I = LBound(FileNames) To UBound(FileNames)
             Msg = Msg & FileNames(i) & vbNewLine
         Next i
         MsgBox Msg
     Else
         MsgBox "No files were selected."
     End If
 End Sub
</source>
   
  

Use filter in Open file dialog

   <source lang="vb">

Sub GetImportFileName2()

   Filt = "Text Files (*.txt),*.txt," & "Lotus Files (*.prn),*.prn," & "Comma Separated Files (*.csv),*.csv," & "ASCII Files (*.asc),*.asc," & "All Files (*.*),*.*"
   FilterIndex = 5
   
   Filename = Application.GetOpenFilename (FileFilter:=Filt, FilterIndex:=FilterIndex, Title:="Select a File to Import",MultiSelect:=True)
   If Not IsArray(Filename) Then
       MsgBox "No file was selected."
       Exit Sub
   End If
   For i = LBound(Filename) To UBound(Filename)
       Debug.Print Filename(i)
   Next i

End Sub

</source>

Namely, I called the following snippet in a button handler:

TextBox1.Text = Application.GetOpenFilename("All files (*.*),*.*", _
        1, "Open the Raw Data Files", , False)
If TextBox1.Text = "False" Then TextBox1.Text = ""

The error said: «Compiler error: Method or data member not found»

Thanks in advance!

asked Apr 15, 2012 at 3:09

stanigator's user avatar

stanigatorstanigator

10.7k34 gold badges92 silver badges128 bronze badges

There is no Application.GetOpenFilename in Word.

You need to use FileDialog instead. Here’s a quick example:

Private Sub CommandButton1_Click()
  Dim s As Variant
  Dim Res As Integer

  Dim dlgSaveAs As FileDialog
  Set dlgSaveAs = Application.FileDialog( _
                   FileDialogType:=msoFileDialogSaveAs)
  Res = dlgSaveAs.Show
  If Not Res = 0 Then
    For Each s In dlgSaveAs.SelectedItems  'There is only one
      MsgBox s
    Next
  End If
End Sub

answered Apr 15, 2012 at 3:32

Ken White's user avatar

Ken WhiteKen White

123k14 gold badges222 silver badges438 bronze badges

3

How often in your VBA code do you have ask for a file name along with its complete path as an input from the user? Most programmers end up using an input box in this situation. However, this is not very convenient for the user. Furthermore, there are chances of “file not found” errors and the requirement for additional error handling code to check whether the inputted file name and path exists. And things get even more messy when multiple files are to be inputted.

What if you can replace this with a single line of code that is easier even for the end user? Well it’s possible using the getopenfilename method.

Let’s start with looking at the syntax. If you wish to jump directly to the examples, click here.

Syntax

expression.GetOpenFilename(FileFilterFilterIndexTitleButtonTextMultiSelect)

where

expression: A variable that represents an Application object.

FileFilter: A string specifying file filtering criteria.

FilterIndex: Specifies the index numbers of the default file filtering criteria, from 1 to the number of filters specified in FileFilter. If this argument is omitted or greater than the number of filters present, the first file filter is used.

Title: Specifies the title of the dialog box. If this argument is omitted, the title is “Open.”

ButtonText: Macintosh only.

MultiSelect: True to allow multiple file names to be selected. False to allow only one file name to be selected. The default value is False.

Return Value: complete file name along with the path

So, let’s look at what the getopenfilename method does in its simplest form.

Sub getFileName()
Dim filename As String
filename = Application.GetOpenFilename()
MsgBox filename
End Sub
  1. First it will open a “File Open” Dialog box. The default location is the “Documents” folder 
  2. The user then navigates to the actual file and selects it. The filename along with the path is stored in the variable filename and displayed to the user in a Message Box.
  3. The variable is set to false if the user cancels on the above window.

Please note, actual file is not opened. Also, If you want to get the current file name and path, you can check the article: Word VBA, Get Current File Path and Name, which very well applies to Excel as well.

Examples

Let’s have a look at few examples of how to use GetOpenFilename

Example 1: Specify a title for the dialog box (default is open)

Sub getFileName1()
Dim filename As String, title As String
title = “Select the file to import”
filename = Application.GetOpenFilename(,,title)
MsgBox filename
End Sub

Here the title of the window is set to “Select the file to import” as seen in the snapshot below:

Here, the filename is displayed in a message box. In real applications, you would use the filename to do something more meaningful.

Workbooks.Open filename

Example 2: Allow selection of multiple files and loop through to get all the file names

Sub getFileName2()
Dim filename As Variant
Dim i As Integer
i = 1
filename = Application.GetOpenFilename(, , , , True)
If filename = False Then
MsgBox "No file Selected"
Exit Sub
End If
For Each element In filename
Cells(i, 1) = element
i = i + 1
Next element
End Sub

Here the last parameter (multiselect) for GetOpenFilename is set to true. So, the user is permitted to select more than one file. The if condition checks whether the user selected at least one file. If not, the code exits from the sub.

To loop through all the filenames selected by the user, the for loop is used and the values are stored in the workbook

The filename is declared as a variant data type. This is because if the user does not select any file, false is returned, which is of type Boolean, else the filename is returned which is a string.

Example 3: Use file filters to filter the type of files.

Sub getFileName3()
Dim filename As Variant
Dim i As Integer
Dim filterStr As String
filterStr = "Text files(*.txt),*.txt," &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; "Image Files(*.jpg;*.png),*.jpg;*.png"
filename = Application.GetOpenFilename(filterStr)
MsgBox filename
End Sub

Here we have set 2 separate filters, one for text files and the other for Images. The first string is the display name for the type of file, while the second string is the actual filter using the wildcard character – *. For example, “Text files” is the display name and file type to be filtered is specified by “*.txt” as seen in the snapshot below.

To use multiple file extensions for a single file filter type, separate the wildcard expressions with semicolons; for example, “Image Files(*.jpg;*.png),*.jpg;*.png”. If FileFilter is omitted, this argument defaults to “All Files (*.*),*.*”.

Example 4:

Putting it all together

Sub getFileName()
Dim filename As Variant
Dim i As Integer
Dim filterStr As String, title As String
filterStr = "Text files (*.txt),*.txt," &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; "Image Files (*.jpg;*.png),*.jpg;*.png"
title = "Select the file to import"
i = 1
filename = Application.GetOpenFilename(filterStr, 2, title, , True)
If filename(1) = False Then
Cells(1, 1) = "No file Selected"
Exit Sub
End If
For Each element In filename
Cells(i, 1) = element
i = i + 1
Next element
End Sub

Note: The getopenfilename method is very similar to msoFileDialogOpen. You can find further details of this in the article: Excel VBA Open File Dialog

So, to summarize, we can effectively use this function to ask users to select a file (to get its name and path) instead having them to type in the entire file

GetOpenFilename is a method that is also an attribute of FSO. This method is used in VBA to find a certain file with a file name and select it. The important factor in this method is the path of the file name provided to open it. Therefore, we can either pass the file name in the function or ask the user to present a file path to select it.

Table of contents
  • Excel VBA Application.GetOpenFilename
    • What Does GetOpenFilename do in Excel VBA?
    • Example of GetOpenFilename in Excel VBA
    • Recommended Articles

Excel VBA Application.GetOpenFilename

There are situations where we need to access the specified file name, which can be possible with VBA coding. To access the file, we need to mention the folder path and file name along with its file extension. To get the file name, many coders will give the VBA input boxVBA InputBox is inbuilt function used to get a value from the user, this function has two major arguments in which one is the heading for the input box and another is the question for the input box, input box function can store only the data types input which it variable can hold.read more as the option to enter the file path and file name. But this is not a good option to practice because when you present an input box in front of the user, they do not always remember the file path, backslashes to separate one folder from another folder, file names, and extension of the files. It makes the input the user gives messier. In the end, everything will screw up, even if there is a small space character mistake. The best way is to replace the input box with VBA’s method called “GetOpenFileName.”

This article will show you how to use VBA GetOpenFileName to get the file name without errors.

VBA GetOpenFilename

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA GetOpenFilename (wallstreetmojo.com)

What Does GetOpenFilename do in Excel VBA?

VBA “GetOpenFileName” allows the user to select the file from the computer we are working on without opening the file.

With the help of the “GetOpenFileName” method, we can present a dialog box in front of the user to select the file in the required folder. “GetOpenFileName” will copy the file location along with the file name and file extension.

Syntax of GetOpenFilename in Excel VBA

Take a look at the syntax of the “GetOpenFilename” method.

VBA GetOpenFilename syntax

  • File Filter: In this argument, we can specify what kind of files to be displayed to select. For example, if you mention “Excel Files,*.xlsx,” it will display only Excel Files saved with the excel extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more “xlsx.” It will display no other files. However, if you ignore it, it will display all kinds of files.
  • Filter Index: With this, we restrict the user from selecting the file type. We can specify the number of filters visible under File Filter.
  • Title: It shows the select file dialogue box title.
  • Button Text: This is only for Macintosh.
  • Multi-Select: TRUE if you want to select multiple files or else FALSE. The default value is FALSE.

Example of GetOpenFilename in Excel VBA

Below are examples of VBA Application.GetOpenFilename.

You can download this VBA GetOpenFilename Excel Template here – VBA GetOpenFilename Excel Template

Let us write a code to get the file name and path address.

Step 1: Start the subroutine.

Code:

Sub GetFile_Example1()

End Sub

VBA GetOpenFilename Example 1

Step 2: Declare a variable as String.

Code:

Sub GetFile_Example1()

   Dim FileName As String

End Sub

VBA GetOpenFilename Example 1-1

Step 3: For this variable, we will assign the GetOpenFileName.

Code:

Sub GetFile_Example1()

  Dim FileName As String

  FileName = Application.GetOpenFilename()

End Sub

VBA GetOpenFilename Example 1-2

As of now, we have ignored all the parameters.

Step 4: Now show the result of the variable in the message box.

Code:

Sub GetFile_Example1()

  Dim FileName As String

  FileName = Application.GetOpenFilename()

  MsgBox FileName

End Sub

Example 1-3

Now run the code through the excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5 or manually. It will show the below dialog box to select the file.

Example 1-4

We will select any one file and click on “OK.”

VBA GetOpenFilename Example 1-5

When we select the file, we get a message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more like this. It shows the full folder path, selected Excel file name, and file extension.

As seen in the above image, we could see all kinds of files.

Now we will add the first parameter, i.e., File Filter, as “Excel Files,*.xlsx.”

Code:

Sub GetFile_Example1()

  Dim FileName As String

  FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xlsx")

  MsgBox FileName

End Sub

VBA GetOpenFilename Example 1-6

If we run this code using the F5 key or manually. We will see only Excel files with the extension “xlsx.”

Example 1-7

Like this, we can use the “VBA Application.GetOpenFileName” method to get the folder path along with the file name and extension.

Recommended Articles

This article has been a guide to VBA GetOpenFilename. Here we learn how to use the VBA Application.GetOpenFileName method to select the files from the folders along with examples. Below are some useful Excel articles related to VBA: –

  • VBA FileCopy
  • VBA FileDialog
  • Operators in VBA
  • Call Subroutine in VBA

4 minute read

If your VBA procedure needs to ask the user for a filename, you could use the InputBox function.

An input box usually isn’t the best tool for this job, however, because most users find it difficult to remember paths, backslashes, filenames, and file extensions.

In other words, it’s far too easy to make a typographical error when typing a filename.

For a better solution to this problem, use the GetOpenFilename method of the Application object, which ensures that your code gets its hands on a valid filename, including its complete path.

The GetOpenFilename method displays the familiar Open dialog box.

The GetOpenFilename method doesn’t actually open the specified file.

This method simply returns the user-selected filename as a string.

Then you can write code to do whatever you want with the filename.

Syntax for the GetOpenFilename method

The official syntax for the GetOpenFilename method is as follows:

' The GetOpenFilename method syntax
object.GetOpenFilename ([fileFilter], [filterIndex], [title],[buttonText], [multiSelect])

The GetOpenFilename method takes the optional arguments shown in below Table.

Arguments What it does
FileFilter Determines the types of files that appear in the dialog box (for example, *.TXT).
You can specify several different filters from which the user can choose.  
FilterIndex Determines which of the file filters the dialog box displays by default.
Title Specifies the caption for the dialog box’s title bar.
ButtonText Ignored
MultiSelect If True, the user can select multiple files.

A GetOpenFilename example

The fileFilter argument determines what appears in the dialog box’s Files of Type drop-down list.

This argument consists of pairs of file filter strings followed by the wild card file filter specification, with commas separating each part and pair.

If omitted, this argument defaults to the following:

' A GetOpenFilename example
All Files (*.*), *.*

Notice that this string consists of two parts:

and

The first part of this string is the text displayed in the Files of Type dropdown list.

The second part determines which files the dialog box displays. For example, . means all files.

The code in the following example brings up a dialog box that asks the user for a filename.

The procedure defines five file filters.

Notice that I use the VBA line continuation sequence to set up the Filter variable; doing so helps simplify this rather complicated argument.

' A GetOpenFilename example
Sub GetImportFileName()
  Dim Finfo As String
  Dim FilterIndex As Integer
  Dim Title As String
  Dim FileName As Variant

  'Set up list of file filters
  If (IsNumeric)NumberOfSheets Then
  FInfo = "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 (FInfo, FilterIndex, Title)

  'Handle return info from dialog box
  If FileName = False Then
    MsgBox "No file was selected."
  Else
    MsgBox "You selected " & FileName
  End If
End Sub

Notice that the FileName variable is declared as a Variant data type.

If the user clicks Cancel, that variable contains a Boolean value (False).

Otherwise, FileName is a string. Therefore, using a Variant data type handles both possibilities.

GetSaveAsFilename Method

The GetSaveAsFilename method works just like the GetOpenFilename method, but it displays the Save As dialog box rather than its Open dialog box.

The GetSaveAsFilename method gets a path and filename from the user but doesn’t do anything with it.

It’s up to you to write code that actually saves the file.

The syntax for this method follows:

' The GetSaveAsFilename method syntax
object.GetSaveAsFilename ([InitialFilename], [FileFilter], [FilterIndex], [Title], [ButtonText])

The GetSaveAsFilename method takes below arguments, all of which are optional.

Arguments What it does
InitialFileName Specifies a default filename that appears in the File Name box.
FileFilter Determines the types of files that appear in the dialog box (for example, *.TXT).
You can specify several different filters from which the user can choose.  
FilterIndex Determines which of the file filters the dialog box displays by default.
Title Specifies the caption for the dialog box’s title bar.

Getting a Folder Name

Sometimes, you don’t need to get a filename; you just need to get a folder name.

If that’s the case, the FileDialog object is just what the doctor ordered.

The following procedure displays a dialog box that allows the user to select a directory.

The selected directory name (or “Canceled”) is then displayed by using the MsgBox function.

' FileDialog example
Sub GetAFolder()
  With Application.FileDialog(msoFileDialogFolderPicker)
    .InitialFileName = Application.DefaultFilePath & ""
    .Title = "Please select a location for the backup"
    .Show
    If .SelectedItems.Count = 0 Then
      MsgBox "Canceled"
    Else
      MsgBox .SelectedItems(1)
    End If
  End With
End Sub

The FileDialog object lets you specify the starting directory by specifying a value for the InitialFileName property.

In this case, the code uses default file path as the starting directory.

Next post will be about VBA UserForms.

Like this post? Please share to your friends:
  • Vba word application commandbars
  • Vba word activedocument words
  • Vba word activedocument close
  • Vba with word 2010
  • Vba with word 2007