Vba getopenfilename excel files

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.GetOpenFilename method (Excel)

vbaxl10.chm133142

vbaxl10.chm133142

excel

Excel.Application.GetOpenFilename

83931dc2-59b3-550b-6ce1-880413fd23d6

04/04/2019

high

Application.GetOpenFilename method (Excel)

Displays the standard Open dialog box and gets a file name from the user without actually opening any files.

Syntax

expression.GetOpenFilename (FileFilter, FilterIndex, Title, ButtonText, MultiSelect)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
FileFilter Optional Variant A string specifying file filtering criteria.
FilterIndex Optional Variant 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 Optional Variant Specifies the title of the dialog box. If this argument is omitted, the title is «Open.»
ButtonText Optional Variant Macintosh only.
MultiSelect Optional Variant 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

Variant

Remarks

This string passed in the FileFilter argument consists of pairs of file filter strings followed by the MS-DOS wildcard file filter specification, with each part and each pair separated by commas. Each separate pair is listed in the Files of type drop-down list box. For example, the following string specifies two file filters—text and addin:

"Text Files (*.txt), *.txt,Add-In Files (*.xla), *.xla"

To use multiple MS-DOS wildcard expressions for a single file filter type, separate the wildcard expressions with semicolons; for example: "Visual Basic Files (*.bas; *.txt), *.bas;*.txt".

If FileFilter is omitted, this argument defaults to "All Files (*.*), *.*".

This method returns the selected file name or the name entered by the user. The returned name may include a path specification. If MultiSelect is True, the return value is an array of the selected file names (even if only one file name is selected). Returns False if the user cancels the dialog box.

This method may change the current drive or folder.

Example

This example displays the Open dialog box, with the file filter set to text files. If the user chooses a file name, the code displays that file name in a message box.

fileToOpen = Application _ 
 .GetOpenFilename("Text Files (*.txt), *.txt") 
If fileToOpen <> False Then 
 MsgBox "Open " & fileToOpen 
End If

[!includeSupport and feedback]

Macro Objective

Our objective is to write a simple macro that prompts the user for a file using a traditional “file open” dialog box.  With this information, we will open the file in the background, copy a range of data, paste it into our active worksheet, then close the user-selected file.

Open the VBA Editor to Start Writing Code

Begin by opening the Visual Basic Editor by pressing ALT-F11 on the keyboard.

The process of presenting a dialog box to open files can be accomplished by accessing a built-in method of the Application object.  The method is called GetOpenFilename.

To use the GetOpenFilename method in a macro, start a new procedure and enter the following code.

Sub Get_Data_From_File()
	Application.GetOpenFilename
End Sub

That’s it!

To test, run the macro to watch as Excel presents us with the Open dialog box.

Notice that the title of the dialog box is “Open” and the default file type filter is to display all file types.

These are customizable options.

If we cancel the macro or select a file and click Open, nothing happens.

This is because the purpose of the GetOpenFilename method is to capture the name of a selected file; nothing more.  The act of opening the file would need to be performed by a separate piece of code.

To make this method useful, we will store the selected file in a variable then use the variable in an Open method to perform the file open operation.

Customizing the GetOpenFilename Method

The syntax for the GetOpenFilename method is:

GetOpenFilename( FileFilter, FilterIndex, Title, ButtonText, MultiSelect)

There are several customizable options with the GetOpenFilename method.

  • FileFilter –defines the pattern by which files are filtered. If you only wish to display text files (files with a .TXT or .CSV extension) you would define the filter as (“Text Files (*.TXT; *.CSV), *.txt; *.csv”).
  • FilterIndex – specifies the default filter from the list supplied in the FileFilter If not defined, the first item in the list is selected as the default.
  • Title – specifies the text to be displayed in the title bar of the dialog box.
  • ButtonText – customizes the text for the buttons (Macintosh only).
  • MultiSelect – Use TRUE to allow multiple files to be selected. Use FALSE to only allow a single file selection.  FALSE is the default choice.

If you’d like to understand how to use MultiSelect correctly, check out the complete course.

Updating the Code

The following are modifications we will make to our existing code:

  • We want to capture the user’s selection in a variable named “FileToOpen”. This will be declared as a string data type.
  • We will use an SET assignment statement to place the user’s selection in the “FileToOpen” variable.
  • We will customize the title of the dialog box to read “Browse for your File & Import Range”.
  • Finally, we will only display Excel files in the dialog box; i.e. files ending in .XLS, .XLSX, .XLSM, or .XLSB.

Using the argument positions to define the options, the updated code will appear as follows:

Sub Get_Data_From_File()
Dim FileToOpen as String
	FileToOpen = Application.GetOpenFilename(“Excel Files (*.xls*), *xls*”, , “Browse for your File & Import Range”)
End Sub

(click image to zoom)

Using the option titles to define the options, the updated code can be made more readable:

Sub Get_Data_From_File()
Dim FileToOpen as String
	FileToOpen = Application.GetOpenFilename(Title:=“Browse for your File & Import Range”, FileFilter:= “Excel Files (*.xls*), *xls*”)
End Sub

(click image to zoom)

Testing the Code

When we run the code, we are presented with the following (note the custom title and filters):

Selecting a file and clicking Open returns us back to Excel with no action.  We’re still not convinced anything happened.

To see the user’s file selection captured as a variable, perform the following:

  1. Add a breakpoint to the “End Sub” step of the code (click the light gray column to the left of the “End Sub” line of code)
  2. Highlight the “FileToOpen” variable
  3. Right-click the highlighted variable and select “Add Watch…
  4. Click OK to add the watch (the Watch window will open automatically)

(click image to zoom)

Run the code.

After selecting a test file and clicking Open, the code will pause on the final line.

Examining the Watch window, we can see the selected file name has been captured and stored in the “FileToOpen” variable.  (NOTE: You can also hover your mouse pointer over any reference to “FileToOpen” and observe a pop-up that displays the variable’s contents.)

(click image to zoom)

Cancelling Our Choice

Suppose the user cancels the Open dialog box.  How will the code respond to this action?

If we launch the code and press the Cancel button without selecting a file, the GetOpenFilename method returns a “False” response and stores it in our “FileToOpen” variable.

(click image to zoom)

Because the “FileToOpen” variable was declared as a string data type, the word “False” will be interpreted as the filename to be opened.

Fixing the Code

Because we want to capture a text string when the user selects a file or capture a Boolean response when the user clicks the Cancel button, we need to change the data type of our “FileToOpen” variable to a Variant data type.

Dim FileToOpen as VariantDim FileToOpen as Variant

If we execute the code with this modification, we can see when we pause on the last line that the “FileToOpen” variable is holding a Boolean FALSE response, not a text response.

(click image to zoom)

We will test the “FileToOpen” variable for the presence of a Boolean FALSE.  If the variable is NOT False, we will execute the remainder of the code.  Otherwise, we will do nothing.

Sub Get_Data_From_File()
Dim FileToOpen As Variant
	FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
	If FileToOpen <> False Then
		(Things happen here)
	End If
End Sub

(click image to zoom)

The below code contains instructions for what is to be performed when a valid filename is supplied.

We have added an additional variable named “OpenBook” to store the contents of the selected file.  The “OpenBook” variable is declared as a Workbook data type.

The additional code will perform the following tasks:

  1. Open the selected file
  2. Store the contents of the file in the variable “OpenBook
  3. Select the first sheet in the workbook
  4. Copy the contents of cells A1 through E20
  5. Paste the copied data as values into the file named “SelectFile” starting in cell A10
  6. Close the workbook selected by the user
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook as Workbook
	FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
	If FileToOpen <> False Then
		Set OpenBook = Application.Workbooks.Open(FileToOpen)
		OpenBook.Sheets(1).Range("A1:E20").Copy
		ThisWorkbook.Worksheets("SelectFile").Range("A10").PasteSpecial xlPasteValues
		OpenBook.Close False
	End If
End Sub

(click image to zoom)

Optimizing the Code

To reduce screen flicker when opening background files, we will add the “Application.ScreenUpdating” toggle to our code.

We will place the toggle at the beginning with a FALSE setting and the same toggle at the end of the code with a TRUE setting.

Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook as Workbook
Application.ScreenUpdating = False
	(Original OPEN and IF operations go here)
Application.ScreenUpdating = True
End Sub

BONUS: Defining Multiple Filters with Defaults

If you wish to filter for a variety of file type; such as Excel files, text files, or all files, you can define your FileFilter argument as follows:

Application.GetOpenFilename("Excel Files (*xls*), *xls*, Text Files (*.TXT), *.txt, All Files (*.*), *.*")

Notice when run, the list has been filtered for Excel files, but you are provided a dropdown to select one of the other two categories of files.

If we add a value to the FilterIndex option, we can pre-select one of the defined filters to be a default choice.  For our three filters, we would define the following values:

1 – for Excel files

2 – for Text files

3 – for All files

The updated code will appear as follows if we wish for Text files to be the default filter selection.

Application.GetOpenFilename("Excel Files (*xls*), *xls*, Text Files (*.TXT), *.txt, All Files (*.*), *.*", 2)

Practice Workbook

Feel free to Download the Workbook HERE.

Excel Download Practice file

Published on: September 26, 2019

Last modified: February 28, 2023

Microsoft Most Valuable Professional

Leila Gharani

I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.

My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.

Excel VBA Tutorial about how to open workbooks and filesOne of the most basic and common operations in Excel is opening a workbook. Regardless of their level (beginner or advanced), virtually every single Excel user has to constantly open workbooks. In fact:

You’ve probably opened a countless amount of Excel workbooks yourself.

If you’re working with VBA, it’s only a matter of time before you need to start creating macros to open Excel workbooks. This Excel tutorial focuses on this basic and common Excel operation:

How to open a workbook using VBA.

I cover this topic by explaining 2 of the most basic macros you can use to open an Excel workbook.

This Excel VBA Open Workbook Tutorial is accompanied by an Excel workbook containing the data and basic structure macros I use below. You can get immediate free access to this example workbook by clicking the button below.

Get immediate free access to the Excel VBA Open Workbook Tutorial workbook example

Both of these macros rely on 1 or both of the following methods:

  • The Workbooks.Open method.
  • The Application.GetOpenFilename method.

Therefore, the second part of this tutorial analyzes both of these methods and goes through each of their parameters. The purpose of this section is to help you get some basic awareness of some of the things you can do when using these methods in your macros.

In addition to help you open workbooks using VBA, the Application.GetOpenFilename method allows you to specify the paths and names of particular Excel workbooks. You’ll likely encounter situations where knowing this (how to allow the user to specify a path and filename) can come in handy.

So let’s take a look at the exact topics that I explain in this blog post:

And let’s start by taking a look at what is, perhaps, the simplest case of opening an Excel workbook using VBA:

How To Open A Workbook Using VBA: The Basic Case

Within Visual Basic for Applications, the method that opens an Excel workbook is the Workbooks.Open method.

The Workbooks.Open method has 15 optional arguments. Each of these 15 optional arguments allows you determine a different aspect of how the Open method opens an Excel workbook.

Since taking a look at 15 arguments at once can get a little overwhelming, let’s start by taking a look at the most basic case: opening an Excel workbook whose name you know. You specify which workbook you want to open by using the Filename argument.

More specifically, the basic VBA statement syntax to open a particular workbook is:

Workbooks.Open Filename:="File_Name"

Or

Workbooks.Open "File_Name"

Where “File_Name” is the file name of the workbook that you want to open with VBA. As shown in the example below, when specifying the workbook’s file name, you must provide the full path and name of the file. I explain how to make this easier below.

The first sample statement above uses named arguments (Filename:=”File_Name”). For the reasons that I explain here, this is my preferred syntax. However, you can also use the second syntax (simply “File_Name”.

Let’s take a look at the Workbooks.Open method in practice:

The following macro (named Open_Workbook_Basic), opens the Excel workbook whose name is “Example – VBA open workbook”. This workbook is saved in the D drive.

vba code open workbook

As mentioned above, notice that when specifying the filename, you must provide the whole file path, name and extension.

open excel workbook path vba

The sample file path above is relatively simple. In particular, there’s no need to go through several sub-folders in order to get to the sample workbook. However…

Probably not many people are able to remember the exact file paths, names and extensions for the files in their laptop. And even then, few would want to type the whole thing every time a new Excel workbook is to be opened. In other words: Having the user type the filename (without browsing) is both:

  • Tedious; and
  • Prone to errors/mistakes.

Since you want to ensure that your macro receives the correct file name (including the whole path and its extension), you’ll usually use slightly more complicated macros than the sample Open_Workbook_Basic Sub procedure displayed above.

Let’s take a look at the simplest way to do this: replicating the way Excel usually works when you browse the computer drive in order to find the particular file you want to open.

How To Open A Workbook Using VBA: Get The File Path With The GetOpenFilename Method

You’re probably quite familiar with the following dialog box:

excel open file dialog

This is the Open dialog box. Excel displays this dialog whenever you browse for purposes of finding and selecting a file to open.

Usually, whenever Excel displays the Open dialog box, you simply need to:

  1. Navigate to the folder containing the Excel workbook you want to open.
  2. Select the file to be opened and click on the Open button in the lower-right corner of the Open dialog.

The following screenshot shows how the Open dialog looks like if you were to open the workbook named “Example – VBA open workbook” that the Open_Workbook_Basic macro above opens.

excel open dialog example 1

You’ll probably agree with me that using this method of choosing the particular Excel workbook that you want to open is much easier than remembering the full file path.

Fortunately, you can replicate this way of operating with VBA. More precisely, you do this by using the Application.GetOpenFilename method.

Excel’s Application.GetOpenFilename method does 2 things:

  1. Displays a customizable Open dialog box; and
  2. Returns the full path/name/extension of the file chosen by the user.

The Application.GetOpenFilename method doesn’t open the file chosen by the user. You still need to rely on the Workbooks.Open method explained above for purposes of actually opening the chosen file. GetOpenFilename simply gives you a mechanism/tool to ask the user for the name(s) of the file(s) that the procedure works with.

The fact that GetOpenFilename doesn’t actually open the file makes this a very versatile method. The reason is that this allows you to use this precise same method in cases in which you need to get the path/name/extension of an Excel workbook for purposes other than opening it.

Therefore, in order to open an Excel workbook through the Open dialog box while using VBA, you need to use both of the following methods:

  • Item #1: The Application.GetOpenFilename method returns the name of the workbook to be opened.
  • Item #2: The Workbooks.Open method actually opens the workbook whose path/name/extension is provided by the Application.GetOpenFilename method.

The Application.GetOpenFilename method has 5 variables. However, just as we did with the Workbooks.Open method, let’s take a look at a very basic piece of VBA code that allows you to:

  1. Browse the available drives for purposes of finding and selecting the Excel workbook you want to open; and
  2. Actually open the selected file.

In such a case, the syntax of the basic VBA statements that you need is as follows:

Dim my_FileName As Variant
my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*")
If my_FileName <> False Then
    Workbooks.Open FileName:=my_FileName
End If

The following screenshot shows the full VBA code of a sample macro called “Open_Workbook_Dialog”.

vba open workbook getopenfilename 1

This Excel VBA Open Workbook Tutorial is accompanied by an Excel workbook containing the data and basic structure macros I use (including the Open_Workbook_Dialog macro). You can get immediate free access to this example workbook by clicking the button below.

Get immediate free access to the Excel VBA Open Workbook Tutorial workbook example

Let’s take a look at each of the statements that makes part of the Open_Workbook_Dialog macro to understand how it proceeds:

Statement #1: Dim my_FileName As Variant

This particular statement is a variable declaration statement. The purpose of declaring a variable in this macro is to store the file name chosen by the user.

This variable declaration statement can be divided in the following 3 items:

vba variable open workbook

Item #1: Dim Statement

As I explain in this macro tutorial, the Dim statement is the most common way to declare a VBA variable.

Item #2: Variable Name

In this particular case, the name of the variable being declared is “my_FileName”.

Item #3: Data Type

my_FileName is declared as being of the Variant data type. This variable is declared as a Variant because the Application.GetOpenFilename method can return different types of data.

Statement #2: my_FileName = Application.GetOpenFilename(FileFilter:=”Excel Files,*.xl*;*.xm*”)

This VBA statement is characterized by the following 2 aspects:

  1. Makes an assignment to the VBA variable my_FileName; and
  2. Uses the GetOpenFilename method that I introduce above.

For purposes of carrying out a closer examination of this statement, I divide it in the following 3 items:

getopenfilename method vba code

Let’s take a look at each of them separately:

Item #1: my_FileName =

The first part of the statement follows the general rule in which a value or expression is assigned to a VBA variable, by using the equal sign (=).

In these cases, the equal sign (=) is an assignment operator. Therefore, it doesn’t represent an equality.

In the case of the Open_Workbook_Dialog macro, the equal sign (=) is assigning:

  • The result of the expression that appears to its right (which I explain in the next section below); to
  • The VBA variable that is on the left side (my_FileName).

Let’s take a look at the items on the right side of the equal sign:

Item #2: Application.GetOpenFilename

This item is the reference to the Application.GetOpenFilename method. As explained above, this particular method:

  1. Displays a customizable Open dialog box; and
  2. Returns the file name chosen by the user (without actually opening it).
    1. If the user selects multiple files (you can determine this by using the MultiSelect argument I explain below, GetOpenFilename returns an array of the file names chosen by the user. This is the case even if the user only selects 1 file.
    2. If the user cancels the Open dialog box (for example, presses the Cancel button), GetOpenFilename returns False.

This leads us to the last item of the statement:

Item #3: (FileFilter:=”Excel Files,*.xl*;*.xm*”)

FileFilter is one of the different parameters of the GetOpenFilename method. As implied by its name, this argument allows you to specify criteria for file-filtering.

It’s an optional argument. However, I include it for purposes of specifying file filtering criteria.

If you omit the FileFilter argument when using the GetOpenFilename method, it defaults to all files (*.*).

In the sample VBA code that appears above (and throughout the rest of this Excel tutorial), I use named arguments. However, that’s not mandatory. If you don’t want to use named arguments, you can use the following statement syntax:

my_FileName = Application.GetOpenFilename("Excel Files,*.xl*;*.xm*")

Let’s take a look at the characteristics of the FileFilter argument:

Characteristic #1: What Does The FileFilter Argument Do.

As explained above, FileFilter determines what are the criteria used for filtering files when the Open dialog box is displayed.

In more practical terms, the FileFilter argument determines what appears in the Files of type drop-down list box on the lower-right corner of the Open dialog box. As shown in the image below, in the case of the Open_Workbook_Dialog macro there’s only one item in the Files of type drop-down list box (Excel Files):

vba filefilter argument example

Characteristic #2: Syntax Of The FileFilter Argument.

The appropriate syntax of the FileFilter Argument is determined by the following rules:

  • Rule #1: Each individual filter is specified by pairing 2 strings as follows:
    • Part #1: A descriptive string. You can omit this part, although I wouldn’t recommend it. In the case of the sample Open_Workbook_Dialog macro, this is “Excel Files”. Notice (in the image above) how this is the text that actually appears in the Files of the type drop-down list of the Open dialog box.
    • Part #2: A comma (,) separating part #1 above and part #2 below.
    • Part #3: The MS-DOS wildcard file-type filter specification. In other words, this part determines how the files are filtered, depending on their type. In the Open_Workbook_Dialog macro, this part is *.xl*;*.xm*.
  • Rule #2: The structure of the file types that you use in the filter specification (part #3 above) is generally (i) an asterisk (*), (ii) a dot (.), and (iii) an indication of the file extension using an asterisk (as wildcard, if necessary) and (if necessary) letters. At the most basic level, the way to specify all files is asterisk dot asterisk (*.*). For example, the Open_Workbook_Dialog macro uses the following 2 file type specifications: *.xl* and *.xm*. Notice how, in both cases: (i) there is an asterisk (*) followed by (ii) a dot (.) and (iii) the first 2 letters of the file extension (xl and xm) followed by an asterisk (*) used as wildcard. Due to the wildcard asterisk, these 2 specifications cover any file extension beginning with .xl (such as .xlsx, .xlsm, .xlsb, .xltx, .xltm, .xls, .xlt, .xlam, .xla and .xlw) or .xm (.xml).
  • Rule #3: As shown by the fact that the Open_Workbook_Dialog macro uses 2 file type specifications, you can include 1 or several file types in a particular filter. When including more than 1 file type in a particular filter, you must separate them with a semi-colon (;). Notice how this is the case in the macro under analysis. More precisely, .xl* and *.xm* are separated by a semi-colon (;) (*.xl*;*.xm*).
  • Rule #4: In addition to the possibility of using multiple file-types, you can create more than 1 actual filter. In such a case, you separate the filters using commas (,). The sample Open_Workbook_Dialog macro above only has one filter. This is determined by the string pairing “Excel Files,*.xl*;*.xm*”. You can, however, separate this single filter into 2 filters (displaying “xl Files” for *.xl* and “xm Files” for *.xm*) as follows:
    vba open workbook filtersThe way to get these 2 filters is to replace the single string pairing “Excel Files,*.xl*;*.xm*” with the following: “xl Files,*.xl*,xm Files,*.xm*”.

Summary Of Statement #2

The final effect of the whole statement explained above is as follows:

  • #1: The Open dialog box is displayed to allow the user to select a file.
  • #2: If the user selects a file, its file name is assigned to the variable called my_FileName.

This leads us to the last statement of the Open_Workbook_Dialog macro, which uses the value of the my_FileName variable.

Statement #3: If my_FileName <> False Then Workbooks.Open FileName:=my_FileName
End If

This is an If… Then… Else statement. These type of statements proceed as follows:

  • Step #1: Carry out a test to determine whether a particular condition is met.
  • Step #2: If the condition is met, a certain group of statements are executed. If the condition isn’t met, the statements aren’t executed.

In the case of the Open_Workbook_Dialog macro, the If… Then… Else statement proceeds as follows:

Step #1: Determine Whether The User Has Select a Workbook

Statement #2 (explained above) assigns the file selected by the user to the variable my_FileName. If the user fails to select a file (by, for example, cancelling the operation), my_FileName returns False.

The test carried out by the If… Then… Else statement under analysis checks whether the my_FileName variable has been assigned a particular file path/name/extension by testing the condition “my_FileName <> False”.

In other words, the condition “my_FileName <> False” is met only when the user has chosen a particular workbook in the Open dialog box displayed by the Application.GetOpenFilename method.

If the condition is met, the If…Then… Else statement proceeds to:

Step #2: Open Excel Workbook

The second part of the If… Then… Else statement we’re looking at is “Workbooks.Open FileName:=my_FileName”.

You already know what this statement does. It’s the Workbooks.Open method described above.

The purpose of the Workbooks.Open method is to open an Excel workbook. In this case, the workbook that is opened is that whose file name has been assigned to the variable my_FileName.

In other words, if the user selects a file when the Open dialog box is displayed, the If… Then… Else statement opens that file.

The Workbooks.Open Method: A Closer Look

As explained at the beginning of this Excel tutorial, Workbooks.Open is the method that you’ll generally use to open Excel workbooks using VBA.

We have already seen the basics of the Workbooks.Open method and its most basic use above. However, in that particular case, I mentioned that this method has 15 different parameters. So far, we’ve only checked one: FileName.

I assume that, if you’re reading this, you want to learn about some more advanced cases of opening Excel workbooks using VBA. In order to do this, let’s take a closer look at the Workbooks.Open method and its different parameters.

The Workbooks.Open Method: Full Syntax

The full syntax of the Workbooks.Open method in Visual Basic for Applications is as follows:

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter,Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

In this case, “expression” stands for a variable representing a Workbook object. In most cases, however, you can simply rely on the syntax used in the sample Open_Workbook_Basic and Open_Workbook_Dialog macros.

In other words, you’ll generally replace “expression” with the Workbooks object itself:

Workbooks.Open

All of the parameters of the Workbooks.Open method, which appear within parentheses above, are optional. Let’s take a look at them!

Parameters Of The Workbooks.Open Method

The following table introduces the 15 optional parameters of the Workbooks.Open method.

Position Name Description
1 FileName Name of workbook to be opened.
2 UpdateLinks Way in which external references/links in the file are updated.
3 ReadOnly Determines whether workbook opens in read-only mode.
4 Format Applies when opening a text file. 

Determines the delimiter character.

5 Password Password required to open protected workbook.
6 WriteResPassword Password required to write in a write-reserved workbook.
7 IgnoreReadOnlyRecommended Applies when a workbook is saved with Read-Only Recommended option enabled. 

Determines whether the read-only recommended message is displayed.

8 Origin Applies when opening a text file. 

Indicates where the file originated.

9 Delimiter Applied when opening a text file and the Format parameter above (No. 4) is a custom character. 

Specifies what is the custom character to be used as delimiter.

10 Editable Applies to: (i) old Excel add-ins (created in Excel 4.0) and (ii) templates. 

When applied to an Excel 4.0 add-in, determines whether add-in is opened as hidden or visible.

If applied to a template, determines whether template is opened for editing, or if a new workbook (based on the template) is created.

11 Notify Applies when a file can’t be opened in read/write mode. 

Determines whether file is added to file notification list (or no notification is requested).

12 Converter Determines what file converter to try upon opening the file.
13 AddToMru Determines whether file is added to list of recent files.
14 Local Determines whether file is saved against language of Excel (usually local) or VBA (usually US-English).
15 CorruptLoad Determines the processing of the file when opened

I provide a more detailed description of the parameters in the sections below. The only exception is the FileName argument, which I explain above.

However, let’s take a closer look at the other parameters:

Argument #2: UpdateLinks

The UpdateLinks argument is the one you can use if you’re interested in determining whether the external references or links within the opened Excel workbook are or aren’t updated.

In other words, UpdateLinks determines how those external references or links are updated. The UpdateLinks parameter can take the following 2 values:

  • 0: In this case, external references/links aren’t updated when the Excel workbook is opened.
  • 3: When using this value, the external references/links are updated when the workbook opens.

The following screenshot shows the VBA code of the sample Open_Workbook_Basic macro where the UpdateLinks parameter has been added and is set to 3.

vba open workbook updatelinks

Since the UpdateLinks parameter isn’t required, you can omit it. In that case, Excel generally defaults to asking the user how links are updated.

Argument #3: ReadOnly

If you set the ReadOnly argument to True, the Excel workbook is opened in read-only mode.

When this argument is added to the sample Open_Workbook_Basic macro, the VBA code looks as follows:

vba open workbook read only

In this case, the Excel workbook is opened as read-only, meaning that any changes made aren’t saved.

When I execute the Open_Workbook_Basic macro, Excel warns me about the opened workbook being read-only. Check out, for example, the screenshot below:

excel open workbook read only

Arguments #4 and#9: Format and Delimiter

The Format argument of the Workbooks.Open method is only relevant when opening text files.

Format determines what the delimiter character is. The delimiter is what allows you to split a single piece of content into different cells. By choosing the value of the Format argument, you specify what delimiter is used.

The following are the possible Format values and the delimiter each of them represents:

  • 1: Tabs.
  • 2: Commas.
  • 3: Spaces.
  • 4: Semicolons.
  • 5: Nothing.
  • 6: A custom character, which you then specify by using the Delimiter argument. The Delimiter argument must be a string. Also, the Delimiter is a single character. If you enter a longer string, the first character of the string is used as delimiter.

If you omit the Format argument when opening a text file, Excel uses whatever delimiter is currently being used.

Since the Open_Workbook_Basic macro makes reference to the Excel workbook named “Example – VBA open workbook.xlxs”, the Format argument isn’t really useful. However, for illustration purposes, the following screenshot shows the VBA code behind this macro using this argument for purposes of setting spaces as the delimiter.

vba open workbook format 2

The following image shows how the VBA code looks like if the Format argument is set to 6 (custom delimiter) and the Delimiter argument is defined as ampersand (&).

vba open workbook delimiter

Arguments #5 and #6: Password and WriteResPassword

You’d generally use the Password and WriteResPassword arguments when you’re working with Excel workbooks that are protected or write-reserved.

Both the Password and WriteResPassword are strings representing a particular password. Their main difference is on what type of protection the Excel workbook being opened has. More precisely:

  • Password: Is the password required to open a protected Excel workbook.
  • WriteResPassword: Is the password required to write in a write-reserved workbook.

If you’re opening an Excel workbook that anyway requires a password and you omit the relevant argument (Password or WriteResPassword, as the case may be), Excel asks the user for the appropriate password.

Let’s assume, for illustrative purposes, that the “Example – VBA open workbook.xlsx” opened by the Open_Workbook_Basic macro is protected by the password “VBA open workbook”. The following screenshot displays the VBA code of the macro with the appropriate Password argument:

vba open workbook password

Argument #7: IgnoreReadOnlyRecommended

Set a particular Excel workbook to be read-only recommended by activating the Read-Only Recommended option when saving the relevant workbook.

The consequence of this is that, when the read-only recommended workbook is opened, Excel displays a message recommending that the workbook is opened as read-only.

excel read only recommended

If the IgnoreReadOnlyRecommended argument is set to True, Excel doesn’t display this particular message when opening the workbook.

The following screenshot displays the VBA code of the Open_Workbook_Basic macro with the IgnoreReadOnlyRecommended argument.

vba open workbook readonlyrecommended

Note that, in this particular case, I’ve deleted the previously added ReadOnly argument. The reason for this is that, if both the ReadOnly and IgnoreReadOnlyRecommended arguments are set to True, Excel simply opens the workbook in read-only mode as required by the ReadOnly argument.

Argument #8: Origin

The Origin argument is only applicable when opening text files. You can use Origin to specify the platform (Microsoft Windows, Mac or MS-DOS) in which the file originated. Indicating the origin of the file allows Excel to map (i) code pages and (ii) Carriage Return/Line Feed properly.

The Origin argument generally takes one of the XlPlatform values, as follows:

  • 1: xlMacintosh.
  • 2: xlMSDOS.
  • 3: xlWindows.

If you omit the Origin argument, Excel uses the operating system of the computer that is opening the file.

The file named “Example – VBA open workbook.xlsx” that is opened by the Open_Workbook_Basic macro isn’t a text file. Therefore, I include the Origin argument in the screenshot below (specifying the origin as Microsoft Windows) only for illustrative purposes:

vba open workbook origin

Argument #9 (Delimiter) is explained above.

Argument #10: Editable

The Editable argument applies to the following types of files:

  • Microsoft Excel 4.0 add-ins. You’ll probably not work too much with these because it’s quite an old format. To give you an idea: Excel 4.0 was released in 1992. Editable doesn’t apply to any add-ins that have been created in later versions of Excel.
  • Excel templates.

The Editable parameter of the Workbooks.Open method works differently depending on which of the above files you’re working with. The general rules are as follows:

When working with Microsoft Excel 4.0 add-ins:

  • Setting Editable to True, opens the relevant add-in in a visible window.
  • Setting Editable to False (which is the default value), opens the add-in as hidden. Additionally, the add-in can’t be unhidden.

When working with a template:

  • Setting Editable to True opens the template for editing.
  • Setting Editable to False (the default value), opens a new Excel workbook that is based on the relevant template.

The workbook opened by the sample Open_Workbook_Basic property is neither a Microsoft Excel 4.0 add-on nor a template. Therefore, the Editable parameter isn’t applicable.

However, for illustrative purposes, the following is an example of how the VBA code to open “Example – VBA open workbook.xlsx” workbooks looks like with the Editable parameter set to True:

vba open workbook editable

Argument #11: Notify

The Notify argument of the Workbooks.Open method applies when you’re opening a file that can’t be opened in read/write mode. If you set the Notify argument to True, Visual Basic for Applications proceeds as follows whenever it encounters such a file:

  • Step #1: The file is opened as read-only and added to the file notification list. The file notification list stores files that could only be opened in read-only mode.
  • Step #2: The status of the file notification list is checked to confirm when the file is available. In more precise terms, the file notification list is polled.
  • Step #3: When the file becomes available, the user is notified about this.

If you omit the Notify argument, or set it to False:

  • The file isn’t added to the file notification list. In other words, no notification that the file is available is requested or received.
  • The attempt to open a file that isn’t available simply fails.

The following screenshot shows the VBA code of the sample Open_Workbook_Basic macro with the Notify argument set to True:

vba open workbook notify

Argument #12: Converter

The Converter argument is applicable whenever you want/need to use file converters. More precisely, you use the Converter parameter to specify the file converter that should be used first when Visual Basic for Applications tries to open a file.

In order to know how to specify a particular file converter, you need to understand the Application.FileConverters property. This property returns information about any file converters that are currently installed.

For example, if you use the Application.FileConverters property without specifying its arguments, the property returns an array with information about all the file converters that are installed. The array is organized as follows:

  • The number of rows is equal to the number of installed file converters. Each converter has its own row.
  • The number of columns is 3. The first column displays the long name of the relevant file converter. The second column contains the path of the converter’s DLL or code resource. The third column shows the file-extension search string.

When working with the Converter argument, you’ll be interested in the row numbers. The reason for this is the way in which you specify the first file converter to use when opening a file:

  • The Converter argument is an index.
  • Each file converter has such an index.
  • The index is the row numbers of the file converters that the Application.FileConverters property (explained above) returns.

There may be situations in which the file converter that you specify with the Converter argument (which is tried first) doesn’t recognize the file being opened. In such cases, the other converters are tried.

Argument #13: AddToMru

AddToMru determines whether the Excel workbook that is being opened is added to the list of recently used files or not. MRU stands for Most Recently Used.

The most recently used list is the list of files that have been recently opened in Excel. You can generally find it in the Open tab of the Backstage View.

excel most recently used list

The default value of AddToMru is False. In this case, the workbook isn’t added to the list of recently used files.

In order to have the Excel workbook added to the list of recently used files, set AddToMru to True. The image below shows how this looks like in the case of the Open_Workbook_Basic macro:

vba open workbook addtomru

Argument #14: Local

The Local parameter makes reference to language and localization settings. Therefore, you may encounter/use this argument if the macro you’re creating is to be used in an international setting where some computers may have different language settings.

More precisely, Local determines against which language are files saved. There are 2 possible values: True or False. Depending on the value you choose, files are saved as follows:

  • True: Files are saved against Excel’s language. This language is generally determined from the control panel settings.
  • False: Files are saved against VBA’s language. This language is generally English. There is a relatively obscure exception to this rule: When the VBA project containing the Workbooks.Open method is an old internationalized XL5/95 project. My guess is that the likelihood of you encountering such a file nowadays is about as high as that of finding the Microsoft Excel 4.0 add-ins which I refer to above.

The following image shows how the Local argument looks like when added to the sample Open_Workbook_Basic macro:

vba open workbook local

Argument #15: CorruptLoad

This is the final argument of the Workbooks.Open method. CorruptLoad determines how a file that has been corrupted is processed upon opening.

The CorruptLoad argument can take 1 of the following 3 values:

  • 0: Represents xlNormalLoad. In this case, the Excel workbook is opened normally. This is the default value, and applies if you don’t specify anything else.
  • 1: Stands for xlRepairFile. In such a case, the Excel workbook is opened in repair mode. In repair mode, Excel tries to recover as much as possible of the workbook being opened.
  • 2: Is the value for xlExtractData. When using this processing mode, the workbook is opened in extract data mode. In extract data mode, Excel extracts the values and formulas from the workbook. Generally, you use extract data mode when the repair mode fails to recover the data/workbook appropriately.

In the following screenshot, the VBA code of the Open_Workbook_Basic macro includes the CorruptLoad parameter. In this case, CorruptLoad is set to 1 (xlRepairFile).

vba open workbook corruptload

When executing this macro, Excel opens the “Example – VBA open workbook” file in repair mode and displays the following message:

excel repair mode dialog

The first time I read the arguments of the Workbooks.Open method, I was slightly surprised that there was no argument to determine whether macros are enabled or disabled upon opening an Excel workbook using VBA.

Eventually, I found out…

How To Enable Or Disable Macros In An Excel Workbook Opened With VBA

Macros are enabled by default whenever you open a file programmatically.

In order to modify the macro security setting that applies when opening an Excel workbook programmatically, you use the Application.AutomationSecurity property. This property allows you to set the security mode that Excel uses when opening files programmatically.

You can generally set the Application.AutomationSecurity property to any of the following 3 constants:

  • 1: Represents msoAutomationSecurityLow which enables all macros. As mentioned at the beginning of this section, msoAutomationSecurityLow is the default value.
  • 2: Stands for msoAutomationSecurityByUI. In this case, the actual security setting is set through the Security dialog box.
  • 3: This is called msoAutomationSecurityForceDisable. This security mode disables all macros and doesn’t show any alerts. This restriction doesn’t apply to Microsoft Excel 4.0 macros. If you open (programmatically) an Excel workbook containing such type of macros, Excel anyway asks the user if the file should be opened or not. This is the case even if the property is set to msoAutomationSecurityForceDisable.

You may want to (generally) reset Application.AutomationSecurity to the default (msoAutomationSecurityLow) after opening the appropriate Excel workbook and before ending the relevant Sub. This reduces the risk of having problems later when a particular solution relies on that default value.

The Application.GetOpenFilename Method: A Closer Look

I introduce and explain the basics of the Application.GetOpenFilename method at the beginning of this Excel tutorial.

The main reason to use the Application.GetOpenFilename method is that it allows your users to select the Excel workbook they want to open without having to remember or type the full path/name/extension. This has 2 main advantages:

  • Advantage #1: Generally, using the Application.GetOpenFilename is more user-friendly than simply relying on the Workbooks.Open method.
  • Advantage #2: The Application.GetOpenFilename ensures that the FileName parameter of the Workbooks.Open method is correct. In other words, GetOpenFilename pretty much guarantees that the path/name/extension argument used by the Open method is valid.

The Application.GetOpenFilename method has 5 arguments. In the sample Open_Workbooks_Dialog macro I’ve only used 1 (FileFilter).

In order to see which other settings you can work with, let’s take a closer look at the syntax of GetOpenFilename and its 4 other parameters:

The Application.GetOpenFilename Method: Full Syntax

The following is the full syntax of the Application.GetOpenFilename method:

expression.GetOpenFilename(FileFilter, FilterIndex, Title, ButtonText, MultiSelect)

“expression” stands for a variable representing an Application object. In practice, you’re like to end up simply using the Application object itself instead of such a variable. Therefore, you’re likely to commonly use the following syntax:

Application.GetOpenFilename

This is, for example, the syntax used in the Open_Workbook_Dialog macro, as shown below:

macro open workbook getopenfilename

I explain the FileFilter argument of the Application.GetOpenFilename method above. Let’s continue to dissect this helpful method by taking a look at the other 4 available parameters:

Parameters Of the Application.GetOpenFilename Method

The following table lists and introduces the 5 parameters of the GetOpenFilename method. All of these arguments are optional.

The arguments of the Application.GetOpenFilename method (generally) focus on the possibility of making some minor modifications to the Open dialog.

Position Name Description
1 FileFilter Determines file filters.
2 FilterIndex Determines the default file filter.
3 Title Determines the title of the (usually called) Open dialog box.
4 ButtonText Applies only when working in the Mac platform. 

Determines the text of the button.

5 MultiSelect Determines whether the user can select multiple files (or not).

I explain all of these arguments (except FileFilter) in more detail below.

Argument #2: FilterIndex

You determine the file filtering criteria using the FileFilter argument. Since this argument allows you to create several filters, Excel needs a way to determine which the default one is.

Here is where the FilterIndex argument comes in:

It “specifies the index numbers of the default file filtering criteria“.

To understand how the FilterIndex parameter works in practice, take a look at the following Open dialog. Notice that there are 2 filters (xl Files and xm Files) in the Files of type drop-down list box.

getopenfilename method filterindex vba

This Open dialog box is displayed when the following version of the Open_Workbook_Dialog macro is executed. Notice how the FileFilter parameter sets 2 file-filtering criteria but there’s no FilterIndex argument.

vba open workbook filefilter

When you omit the FilterIndex argument, Excel displays the first filter. In the case above, this filter is xl Files.

Let’s assume, however, that you want a different filter to be displayed as default. The following image shows how you can modify the Open_Workbook_Dialog macro to add the FilterIndex argument and select the second filter (xm Files) as the default filter.

vba open workbook filterindex

The resulting Open dialog box looks as follows. Notice that, now, the default filter is indeed xm Files, even though it continues to be in the second position within the Files of type drop-down list box.

excel open dialog filterindex

In the image above, you may also notice that the sample Excel workbook named “Example – VBA open workbook.xlsx” doesn’t appear as it does in previous screenshots. This is because it has been filtered out by the xm Files filter.

The xm Files filter is used to display only files whose extension begins with the letters “xm”. These are generally files that use the .xml format. In fact, the xm File filter can probably be specified more specifically with the string pair “xm Files,*.xml”.

The FilterIndex argument can only take values between 1 and the number of file filters that you’ve specified with the FileFilter argument. In the case above, this upper limit is 2.

If you set a value that is larger than the number of filters that actually exist, Excel uses the first file filter. In the case of the Open_Workbook_Dialog macro above, this would happen whenever the FilterIndex parameter has a value equal to or larger than 3. The VBA code for this case appears in the following image:

vba open workbook default filterindex

In this case, the Open dialog box is as follows. Notice how, as expected, the default filter is xl Files (the first filter).

excel open dialog filterindex default

Argument #3: Title

The Title argument of the Application.GetOpenFilename method is kind self-explanatory:

It allows you to determine the title of the dialog box that is usually known as the Open dialog. As you probably expect, if you omit this parameter, the title of the dialog box is “Open”.

The following image shows how the VBA code behind the Open_Workbook_Dialog macro looks like if the Title argument is set to “Example VBA Open Workbook”:

vba open workbook title

Notice how the new title appears at the top of the (previously Open) dialog box:

example vba open workbook dialog 1

Argument #4: ButtonText

The ButtonText only applies in Mac platforms. When used in Windows, the argument is ignored.

It allows you to determine the text that appears in the action button. This is the button regularly known as the Open button.

vba open workbook buttontext

The fact that you can’t change the text of the Open button when working in Windows may lead to slightly confusing situations:

Imagine, for example, that you’re using the GetOpenFilename method for a purpose other than opening an Excel workbook. In such cases, the button will continue to say “Open”, even though the file isn’t really opened later.

Argument #5: MultiSelect

The MultiSelect argument of the Application.GetOpenFilename method allows you to determine whether the user can select multiple file names at the same time.

By default, users are only allowed to select a single file. In this case, the value of the MultiSelect parameter is False. If you want to explicitly specify that MultiSelect is False, the VBA code of the Open_Workbook_Dialog macro looks as follows:

Application.GetOpenFilename | If myFilename Then | Workbooks.Open | End If

If you set MultiSelect to True, users can select several file names. If you set MultiSelect to True, the Application.GetOpenFilename method returns an array with the selected filenames. This is the case even if you select a single file. Therefore, when you enable MultiSelect, you must make the following 2 modifications to the VBA code example that appears above:

  1. Set the MultiSelect parameter to True.
  2. Treat the my_FileName variable as an array. This involves, in particular, modifying the way in which you open the workbook(s) whose filenames are returned by the GetOpenFilename method. If you only set MultiSelect to True (#1 above) but fail to appropriately handle the array that GetOpenFilename returns, VBA is likely to return a Type mismatch error.

Conclusion

2 of the most common operations when working with Excel are:

  • Opening Excel workbooks; and
  • Specifying file paths and names.

Workbooks.Open and Application.GetOpenFilename are the basic methods that you use for purposes of carrying out these operations with VBA. Therefore, you’re likely to use both of these methods quite bit when creating macros and working with Visual Basic for Applications.

Fortunately, if you’ve read this Excel tutorial, you’re knowledgeable enough to use both the Open and GetOpenFilename methods. In addition to knowing what their purpose is, you’ve seen what each of their parameters is and what they allow you to specify.

Хитрости »

17 Июнь 2015              147433 просмотров


Диалоговое окно выбора файлов/папки

Часто при работе с файлами и написании кодов начинающие «кодить» в VBA сталкиваются с необходимостью предоставить пользователю возможность самостоятельного выбора файлов: либо всех в указанной папке, либо каких-то отдельных. Конечно, можно жестко в коде написать нечто вроде: «C:DocumentsFilesКнига1.xls», но это требует не только наличия именно диска С, но и полной структуры папок и имен файлов. Это очень неудобно в большинстве случаев и куда чаще необходимо дать пользователю возможность самому указать имя файла. Записывать в ячейку листа полный путь и имя весьма непрактично и часто для неискушенного пользователя вызывает только «отторжение» от программы. В статье Просмотреть все файлы в папке я приводил пример кода, который просматривает все файлы в указанной папке и папка при этом выбирается сами пользователем из привычного по работе с Windows диалога. Там используется диалог выбора папок. Именно на этом я и хочу сделать акцент в этой статье — рассказать про некоторые способы вызова подобных диалогов для выбора файлов или папки. Так же обращу внимание на некоторые вещи, которые следует учитывать при использовании того или иного типа диалогов.

  • Диалог выбора файлов Applicaton.GetOpenFileName
  • Диалог выбора файлов FileDialog(msoFileDialogFilePicker)
  • Диалог выбора папки FileDialog(msoFileDialogFolderPicker)
  • Диалог выбора папки через Shell
  • Диалог сохранения файла SaveAs

Если рассматривать наиболее простые варианты, то их два. Выбрать файлы можно через Applicaton.GetOpenFileName или через Application.FileDialog. Отличия в них есть, но я заострю внимание на главном: GetOpenFileName будет работать в любой версии Excel, а класс FileDialog только начиная с Excel 2002, т.к. именно в этой версии впервые был использован класс FileDialog. Это стоит учитывать при разработке.

Диалог выбора файлов Applicaton.GetOpenFileName

Параметры:

Application.GetOpenFilename([FileFilter], [FilterIndex], [Title], [ButtonText], [MultiSelect])
По сути я часто использую именно его, т.к. это универсальный метод и в нем есть все, что лично мне необходимо: выбрать определенные типы файлов позволяет, возможность запрета выбора нескольких файлов сразу есть.

FileFilter Указываются типы файлов, которые будут отображаться в диалоговом окне выбора. Например, если указать «Excel files(*.xls*),*.xls*», то возможно будет выбрать только файлы Excel(с расширением, начинающимся на .xls — .xls, .xlsx, .xlsb, .xlsm и т.д.). Если указать «Text files(*.txt),*.txt», то можно будет выбрать только текстовые файлы с расширением .txt. Так же можно указать более одного типа расширений: «Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt». По умолчанию тип файлов в диалоговом окне будет принадлежать первому указанному типу файлов(*.xls*). Но можно указать любой из перечисленных типов при помощи аргумента FilterIndex. Так же можно указать выбор любых типов файлов: «All files(*.*),*.*»
FilterIndex Если аргументом FileFilter указано более одного типа файлов(расширений), то этот аргумент указывает какой именно тип использовать. Например, следующая строка по умолчанию назначает выбор текстовых типов файлов:

avFiles = Application.GetOpenFilename _
    ("Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", 2, _
     "Выбрать текстовые или Excel файлы", , True)

Атрибут FilterIndex

Title Текст заголовка диалогового окна. Если указать «Выбрать текстовые или Excel файлы», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Открытие документа»)
ButtonText Данный аргумент доступен только для ПК под управлением Macintosh(MAC). Назначает текст для кнопки диалогового окна Открыть. Для владельцев Windows этот текст всегда будет «Открыть»
MultiSelect Указывает, может быть выбран только один файл или несколько:

  • True — можно будет выбрать более одного файла для обработки(через Shift или Ctrl или простым выделением мышью внутри окна)
  • False — можно будет выбрать только один файл

По умолчанию принимает значение False
Выбора только одного файла:

avFiles = Application.GetOpenFilename _
    ("Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", 2, _
     "Выбрать текстовые или Excel файлы", , False)

Выбор нескольких файлов:

avFiles = Application.GetOpenFilename _
    ("Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", 2, _
     "Выбрать текстовые или Excel файлы", , True)

Пример применения диалога Application.GetOpenFilename

Sub ShowGetOpenDialod()
    Dim avFiles
    'по умолчанию к выбору доступны файлы Excel(xls,xlsx,xlsm,xlsb)
    avFiles = Application.GetOpenFilename _
                ("Excel files(*.xls*),*.xls*", 1, "Выбрать Excel файлы", , False)
    If VarType(avFiles) = vbBoolean Then
        'была нажата кнопка отмены - выход из процедуры
        Exit Sub
    End If
    'avFiles - примет тип String
    MsgBox "Выбран файл: '" & avFiles & "'", vbInformation, "www.excel-vba.ru"
End Sub

В данном случае совершенно неважно указан ли выбор только одного файла или нескольких. Может поменяться только способ обработки полученного результата. Если параметр MultiSelect установлен в False, то переменная avFiles примет тип String, т.е. это будет одна строка. Предположим, что была выбрана книга Excel. Тогда открыть её можно будет как обычно это делается при использовании переменной:

Если же параметр MultiSelect установлен в True, то переменная avFiles примет тип Array — массив строк, в котором будут записаны все пути и имена выбранных файлов. Обрабатывать в таком случае следует циклом:

'avFiles - примет тип Array
    For Each x In avFiles
        Workbooks.Open x
    Next

В приложенном к статье файле приведены две процедуры с использованием этого типа диалога и обработкой файлов с параметром MultiSelect, установленным в True и False.


 
Диалог выбора файлов FileDialog(msoFileDialogFilePicker)

У этого диалога тоже есть параметры и они очень схожи с таковыми в Application.GetOpenFilename:
Ниже в статье примера кода с применением всех описанных параметров

AllowMultiSelect Указывает, может быть выбран только один файл или несколько:

  • True — можно будет выбрать более одного файла для обработки(через Shift или Ctrl или простым выделением мышью внутри окна)
  • False — можно будет выбрать только один файл
Title Текст заголовка диалогового окна. Если указать «Выбрать текстовые или Excel файлы», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Открытие документа»)
Filters Перечисляются типы файлов, которые будут отображаться в диалоговом окне выбора. Для добавления типа файла(расширения) необходимо использовать метод Add:
.Filters.Add([Description],[Extensions],[Position])

  • Description — описание типа файлов. Произвольный текст, указывающий тип файлов. Например «Рисунки» или «Файлы Excel».
  • Extensions — расширения файлов. Непосредственно перед расширением обязательно должна стоять звездочка и точка: *.xls. Иначе диалог выдаст ошибку. Для перечисления нескольких расширений используется разделитель в виде точки-с-запятой: «*.xls*;*.xla*» или «*.xls;*.xlsx;*.xlsm». Звездочка после расширения заменяет любой набор символов или ни одного. Например, при указании «*.xls*» будет возможным выбрать любые файлы, расширение которых начинается на .xls: .xls,.xlsx,.xlsm,.xlsb и т.д., но нельзя будет выбрать файлы с расширением .xla,.xlam и тем более .doc или .txt. Если необходимо осуществить выбор любого типа файлов, то необходимо просто очистить фильтр и не добавлять никакие типы: .Filters.Clear
  • Position — указывает, каким по счету в списке будет тип файлов. На рисунке ниже первым идет тип «Excel files», а вторым «Text files»:
    Атрибут FilterIndex
  • Тип файлов, который будет показан по умолчанию при вызове диалога определяется свойством FilterIndex диалога FileDialog.
    Важный момент: диалог, вызванный в одном сеансе Excel сохраняет добавленные ранее типы файлов. Поэтому перед назначением новых типов необходимо выполнить очистку фильтра:
    .Filters.Clear

Каждый новый тип файлов добавляется новым Add:

.Filters.Add "Excel files", "*.xls*;*.xla*", 1 'добавляем возможность выбора файлов Excel
.Filters.Add "Text files", "*.txt", 2 'добавляем возможность выбора текстовых файлов
FilterIndex Назначает тип файлов, который будет выбран по умолчанию из всех перечисленных в коллекции Filters при вызове диалога
InitialFileName Этим параметром можно задать начальную папку, на которой будет открыт диалог:

.InitialFileName = "С:Temp"

Если при этом еще добавить имя файла, то в поле диалога Имя файла будет так же отображено это имя:

.InitialFileName = "С:TempКнига1.xlsx"

Я лично не рекомендую указывать имя файла, т.к. после показа диалога этот файл автоматически будет выбран, что не всегда бывает правильным. Но все зависит от задач. Если пользователь не выберет самостоятельно ни одного файла, то ответом диалога будет именно файл с указанным именем(Книга1.xlsx). Если такого файла не окажется в папке, то диалог выдаст предупреждение, что такого файла нет.

InitialView Данный параметр определяет внешний вид и структуру окна диалога. Доступно 9 вариантов:

  • msoFileDialogViewDetails
  • msoFileDialogViewLargeIcons
  • msoFileDialogViewList
  • msoFileDialogViewPreview
  • msoFileDialogViewProperties
  • msoFileDialogViewSmallIcons
  • msoFileDialogViewThumbnail
  • msoFileDialogViewTiles
  • msoFileDialogViewWebView

При использовании данного параметра следует учитывать, что на разных операционных системах могут быть доступны не все варианты. Поэтому прежде чем использовать лучше убедиться, что на конечных ПК поддерживается указанный тип. В принципе ничего страшного не произойдет — будет просто показано окно с видом по умолчанию. Но куда правильнее в разработке придерживаться однотипного вида на всех ПК.

SelectedItems Возвращает коллекцию выбранных файлов. В отличии от Application.GetOpenFilename всегда возвращается массив строк, поэтому можно всегда использовать цикл для открытия файлов, даже если параметр AllowMultiSelect установлен в False:

For Each x In .SelectedItems
    Workbooks.Open x
Next

Так же можно отбирать только отдельные файлы по индексам или организовать цикл иначе:

For lf = 1 to .SelectedItems.Count
    x = .SelectedItems(lf)
    Workbooks.Open x
Next

Нумерация строк в SelectedItems всегда начинается с 1

Show Пожалуй, самый важный метод в диалоге — отвечает за показ диалога. При этом метод Show возвращает ответ в виде целого числа:

  • -1 — выбор файлов был сделан и нажата кнопка Открыть
  • 0 — была нажата кнопка отмены

Это можно(точнее нужно!) использовать, чтобы не продолжать выполнение кода, если нажата кнопка Отмены:

If .Show = 0 Then Exit Sub 'была нажата кнопка отмены

Пример вызова диалога выбора файлов:

Sub ShowFileDialog()
    Dim oFD As FileDialog
    Dim x, lf As Long
    'назначаем переменной ссылку на экземпляр диалога
    Set oFD = Application.FileDialog(msoFileDialogFilePicker)
    With oFD 'используем короткое обращение к объекту
    'так же можно без oFD
    'With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .Title = "Выбрать файлы отчетов" 'заголовок окна диалога
        .Filters.Clear 'очищаем установленные ранее типы файлов
        .Filters.Add "Excel files", "*.xls*;*.xla*", 1 'устанавливаем возможность выбора только файлов Excel
        .Filters.Add "Text files", "*.txt", 2 'добавляем возможность выбора текстовых файлов
        .FilterIndex = 2 'устанавливаем тип файлов по умолчанию - Text files(Текстовые файлы)
        .InitialFileName = "С:TempКнига1.xlsx" 'назначаем папку отображения и имя файла по умолчанию
        .InitialView = msoFileDialogViewDetails 'вид диалогового окна(доступно 9 вариантов)
        If .Show = 0 Then Exit Sub 'показывает диалог
        'цикл по коллекции выбранных в диалоге файлов
        For lf = 1 To .SelectedItems.Count
            x = .SelectedItems(lf) 'считываем полный путь к файлу
            Workbooks.Open x 'открытие книги
            'можно также без х
            'Workbooks.Open .SelectedItems(lf)
        Next
    End With
End Sub

 
Диалог выбора папки

Диалог выбора папки необходим в случаях, когда файлов в папке много и обработать нужно все эти файлы. Пример такой обработки я уже выкладывал в статье Просмотреть все файлы в папке. Здесь проще всего использовать появившийся в 2002 Excel диалог Application.FileDialog. Его параметры практически такие же, как у Application.FileDialog(msoFileDialogFilePicker) только их меньше доступно для применения:

Title Текст заголовка диалогового окна. Если указать «Выбрать папку с отчетами», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Открыть папку»)
InitialFileName Этим параметром можно задать начальную папку, на которой будет открыт диалог:

.InitialFileName = "С:Temp"
InitialView Данный параметр определяет внешний вид и структуру окна диалога. Доступно 9 вариантов:

  • msoFileDialogViewDetails
  • msoFileDialogViewLargeIcons
  • msoFileDialogViewList
  • msoFileDialogViewPreview
  • msoFileDialogViewProperties
  • msoFileDialogViewSmallIcons
  • msoFileDialogViewThumbnail
  • msoFileDialogViewTiles
  • msoFileDialogViewWebView

При использовании данного параметра следует учитывать, что на разных операционных системах могут быть доступны не все варианты. Поэтому прежде чем использовать лучше убедиться, что на конечных ПК поддерживается указанный тип. В принципе ничего страшного не произойдет — будет просто показано окно с видом по умолчанию. Но куда правильнее в разработке придерживаться однотипного вида на всех ПК.

SelectedItems Возвращает коллекцию с одним элементом, в котором содержится путь к выбранной папке. Нумерация строк в SelectedItems всегда начинается с 1, но т.к. выбор нескольких папок невозможен, то всегда указывается 1: x = .SelectedItems(1)
ButtonName Назначает текст кнопки, которой подтверждается выбор папки. Может содержать не более 51 знака(чего как правило достаточно).
Show Метод, который вызывает показ диалога с выбранными параметрами. Возвращает ответ в виде целого числа:

  • -1 — папка выбрана и нажата кнопка Открыть
  • 0 — была нажата кнопка отмены

Это можно(точнее нужно!) использовать, чтобы не продолжать выполнение кода, если нажата кнопка Отмены:

If .Show = 0 Then Exit Sub 'была нажата кнопка отмены

Пример вызова диалога выбора папки:

Sub ShowFolderDialog()
    Dim oFD As FileDialog
    Dim x, lf As Long
    'назначаем переменной ссылку на экземпляр диалога
    Set oFD = Application.FileDialog(msoFileDialogFolderPicker)
    With oFD 'используем короткое обращение к объекту
    'так же можно без oFD
    'With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Выбрать папку с отчетами" '"заголовок окна диалога
        .ButtonName = "Выбрать папку"
        .Filters.Clear 'очищаем установленные ранее типы файлов
        .InitialFileName = "C:Temp" '"назначаем первую папку отображения
        .InitialView = msoFileDialogViewLargeIcons 'вид диалогового окна(доступно 9 вариантов)
        If .Show = 0 Then Exit Sub 'показывает диалог
        'цикл по коллекции выбранных в диалоге файлов
        x = .SelectedItems(1) 'считываем путь к папке
        MsgBox "Выбрана папка: '" & x & "'", vbInformation, "www.excel-vba.ru"
    End With
End Sub

 
Диалог выбора папки через Shell

Диалог Application.FileDialog(msoFileDialogFolderPicker) всем хорош и удобен, кроме одного: как я уже упоминал, он стал доступен из VBA только начиная с 2002 Excel. Плюс, описанные выше диалоги не работают в Outlook — он просто лишен хоть какой-либо реализации выбора папок или файлов. Поэтому дополню статью еще одним вариантом показа диалога выбора папки — с помощью объекта Shell. Этот вариант выбора папки будет работать и в Outlook и в любом другом приложении.

Shell.BrowseForFolder([Hwnd], [sTitle], [iOptions], [vRootFolder])

Hwnd Дескриптор окна, к которому будет относится диалог. Как правило указывается 0
sTitle Поясняющий текст, который будет отображен в диалоге. Подобие заголовка окна. Может быть любым текстом, например «Выбрать папку с отчетами»
iOptions Дополнительные параметры для диалога. Рекомендуется использовать 0. Но можно попробовать и пару других вариантов. Например, если указать 20, то в диалоговом окне появится дополнительное текстовое поле, в котором будет отображено имя выбранной папки.
vRootFolder Аналогично InitialFileName в рассмотренных выше диалогах. Задает начальную папку, на которой диалог будет открыт после запуска.

Диалог выбора папки - Shell
Пример вызова диалога выбора папки через Shell:

Sub GetFolderDialog_Shell()
    On Error Resume Next
    Dim objShellApp As Object, objFolder As Object, ulFlags
    Dim x As String
    Set objShellApp = CreateObject("Shell.Application")
    'ulFlags - числовой код, определяющий вид отображаемого окна и некоторые параметры
    '    ulFlags = 0     - наиболее часто применяемый. Лучше использовать всегда именно 0
    '    ulFlags = 1     - не отображать Корзину
    '    ulFlags = 2     - не включать сетевые папки
    '    ulFlags = 20    - добавляется тестовое поле с отображением имени выбранной папки
    '    ulFlags = 16    - отображать EditBox для ввода полного пути с клавиатуры
    '    ulFlags = 16384 - можно так же выбирать файлы.
    'Некоторые константы можно комбинировать. Например если указать 1 + 16384 - то можно будет выбирать файлы
 
    ulFlags = 0
    Set objFolder = objShellApp.BrowseForFolder(0, "Выбрать папку с отчетами", ulFlags, "C:Temp")'"
    x = objFolder.Self.Path 'записываем в переменную путь к папке
    If Err.Number <> 0 Then
        MsgBox "Папка не выбрана!", vbInformation, "www.excel-vba.ru"
    Else
        MsgBox "Выбрана папка: '" & x & "'", vbInformation, "www.excel-vba.ru"
    End If
End Sub

Конечно, диалог подобный выглядит довольно убого, особенно на современных операционных системах. Но он работает в любых версиях офиса и в любом приложении, в том числе в Outlook. Порой это бывает полезней красоты.

Скачать пример:

  Tips_Macro_GetOpenFileFolder.xls (100,0 KiB, 3 740 скачиваний)


 
Диалог сохранения файла SaveAs

Еще один вид диалогового окна — запрос имени и места сохранения файла.
Параметры:

Application.GetSaveAsFilename([InitialFileName], [FileFilter], [FilterIndex], [Title], [ButtonText])
Универсальный диалог, работающий во всех версиях Excel, начиная с 2000

InitialFileName Можно указать путь и имя файла, которые будут использованы в качестве шаблона для сохранения. По умолчанию в диалоге отображается папка, которая была использована в последний раз в текущем сеансе Excel. Если диалог вызывается впервые, то будет показана для сохранения файлов по умолчанию(задается из самого Excel: Файл(File)Параметры(Options)Сохранение(Save)Расположение локальных файлов по умолчанию(Default local file location)).
Показываем диалог со стартовой папкой на той книге, в которой сам макрос, без указания имени сохраняемой книги:

sToSavePath = Application.GetSaveAsFilename(InitialFileName:=ThisWorkbook.Path)

Показываем диалог со стартовой папкой на той книге, в которой сам макрос и именем сохраняемой книги «SaveAs.xlsm»:

sToSavePath = Application.GetSaveAsFilename(InitialFileName:="SaveAs.xlsm", FileFilter:="Excel files (*.xlsm), *.xlsm")

Здесь следует обратить внимание на один важный момент: если необходимо помимо стартовой папки указать еще и имя файла, то в обязательном порядке надо указывать так же аргумент FileFilter. Если его не указывать, то InitialFileName просто откроет указанную папку, т.к. не поймет файлы какого типа надо отображать. Либо вместо «SaveAs.xlsm» надо будет указывать «SaveAs.*», что я лично настоятельно не рекомендую делать.
Несмотря на возможность указать имя файла его можно изменить прямо в диалоговом окне, что тоже порой правильнее. Например, чтобы убедиться в том, что имя файла указано пользователем.

FileFilter Указываются типы файлов, которые будут отображаться в диалоговом окне выбора. Должен совпадать с тем типом, с которым собираемся сохранять файл. Например, если указать «Excel files(*.xls*),*.xls*», то возможно будет выбрать только тип файлов Excel(с расширением, начинающимся на .xls — .xls, .xlsx, .xlsb, .xlsm и т.д.). Если указать «Text files(*.txt),*.txt», то только текстовые файлы с расширением .txt. Так же можно указать более одного типа расширений: «Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt». По умолчанию тип файлов в диалоговом окне будет принадлежать первому указанному типу файлов(*.xls*). Но можно указать любой из перечисленных типов при помощи аргумента FilterIndex. Так же можно указать выбор любых типов файлов: «All files(*.*),*.*»
FilterIndex Если аргументом FileFilter указано более одного типа файлов(расширений), то этот аргумент указывает какой именно тип использовать. Например, следующая строка по умолчанию назначает выбор и сохранение файла в текстовый:

avFiles = Application.GetSaveAsFilename _
    (InitialFileName:=ThisWorkbook.Path, FileFilter:="Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", FilterIndex:=2)

Атрибут FilterIndex

Title Текст заголовка диалогового окна. Если указать «Выбрать текстовые или Excel файлы», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Сохранение документа»)
ButtonText Данный аргумент доступен только для ПК под управлением Macintosh(MAC). Назначает текст для кнопки диалогового окна Сохранить. Для владельцев Windows этот текст всегда будет «Сохранить»

Что еще важно знать: сам по себе вызов диалога GetSaveAsFilename ничего не сохраняет — он только создает путь для сохраняемого файла. Сохранять придется принудительно после выбора места и имени.
Пример применения диалога Application.GetSaveAsFilename

Sub ShowGetSaveAsDialod()
    Dim sToSavePath
    sToSavePath = Application.GetSaveAsFilename( _
             InitialFileName:=ThisWorkbook.Path, _
             FileFilter:="Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", _
             FilterIndex:=2, _
             Title:="Сохранить файл")
    'если нажали Отмена - завершаем процедуру ничего не сохраняя
    If VarType(sToSavePath) = vbBoolean Then
        Exit Sub
    End If
    'непосредственно сохранение файла
    ThisWorkbook.SaveAs Filename:=sToSavePath, FileFormat:=ThisWorkbook.FileFormat
End Sub

Здесь тоже есть нюанс — метод SaveAs имеет два важных аргумента:
1. Filename — путь и имя сохраняемого файла. Здесь должно быть все понятно. Указываем то, что выбрали в диалоге.
2. FileFormat — формат сохраняемого файла. При этом не текстовое представление(как в диалоге «xls» или «txt»), а одна из предустановленных констант формата файла. Вот основные константы:

Константа Excel Числовая константа Расшифровка
xlOpenXMLWorkbookMacroEnabled 51 xlsm — книга Excel
xlOpenXMLWorkbookMacroEnabled 52 xlsm — книга Excel с поддержкой макросов
xlExcel12 50 xlsb — двоичная книга Excel (с поддержкой макросов)
xlOpenXMLAddIn 55 xlam — надстройка Excel
xlOpenXMLTemplate 54 xltx — шаблон Excel
xlOpenXMLTemplateMacroEnabled 53 xltm — шаблон Excel с поддержкой макросов
xlExcel8 56 xls — книга Excel(97 — 2003)
xlAddIn 18 xla — надстройка Excel(97 — 2003)
xlTemplate 17 xlt — шаблон Excel(97 — 2003)
xlCurrentPlatformText -4158 txt — текстовый файл с разделителями табуляции
xlUnicodeText 42 txt — текстовый файл в кодировке Юникод
xlCSV 6 csv — CSV(разделитель запятая)
xlCSVMSDOS 24 csv — CSV(MS — DOS)
XlFileFormat 62 csv — CSV UTF-8(разделитель запятая)
xlTypePDF 0 pdf — файл в формате PDF

Пример использования констант в диалогах Application.GetSaveAsFilename
Сохраняем файл с форматом xlsm — файл с поддержкой макросов. Для этого ищем в таблице выше расширение xlsm и берем либо константу Excel либо числовую константу:

Sub ShowGetSaveAsDialod()
    Dim sToSavePath
    sToSavePath = Application.GetSaveAsFilename( _
             InitialFileName:=ThisWorkbook.Path & "Report.xlsm", _
             FileFilter:="Excel files(*.xlsm),*.xlsm")
    'если нажали Отмена - завершаем процедуру ничего не сохраняя
    If VarType(sToSavePath) = vbBoolean Then
        Exit Sub
    End If
    'непосредственно сохранение файла
    'используем встроенную константу Excel
    ThisWorkbook.SaveAs Filename:=sToSavePath, FileFormat:=xlOpenXMLWorkbookMacroEnabled
    'используем числовую константу
    'ThisWorkbook.SaveAs Filename:=sToSavePath, FileFormat:=52
End Sub

Любой метод: либо числовая константа, либо встроенная работают одинаково. Вопрос лишь в том, что лично для Вас будет удобнее и нагляднее.

Так же см.:
Работа с диалогами
Как запретить сообщения?


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

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

Like this post? Please share to your friends:
  • Vba from excel to word table
  • Vba from excel to powerpoint
  • Vba from excel to html
  • Vba from excel 2010
  • Vba from excel 2007