Excel vba запустить файл

Запуск исполняемой программы с помощью функции Shell в VBA Excel. Синтаксис функции Shell, ее параметры, возвращаемые значения, примеры.

Shell – это функция, которая запускает указанную исполняемую программу и возвращает значение Variant (Double), представляющее идентификатор задачи запущенной программы, или возникает ошибка, если функция Shell не может запустить указанную программу.

Синтаксис

Синтаксис функции Shell:

Shell(pathname, [windowstyle])

Если значение функции присваивается переменной, параметры должны быть заключены в скобки. Если функция Shell используется только для запуска программы из кода VBA Excel, параметры должны быть указаны без скобок.

Параметры

Параметры функции Shell:

Параметр Описание
pathname Обязательный параметр. Значение типа Variant (String), задающее имя программы, которую требуется выполнить, и которое может включать диск, каталоги и папки, а также дополнительные параметры при использовании cmd.
windowstyle Необязательный параметр. Значение типа Variant (Integer), задающее стиль окна, в котором будет запущена программа. Если аргумент windowstyle опущен, программа запускается в свернутом окне и получает фокус.

Константы

Константы VBA Excel, задающие стиль окна (windowstyle):

Константа Значение Описание
vbHide 0 Окно скрыто, фокус переходит к скрытому окну.
vbNormalFocus 1 Окно восстанавливает свое исходное положение и размер, а также получает фокус.
vbMinimizedFocus 2 Окно отображается в виде значка, а также получает фокус.
vbMaximizedFocus 3 Окно разворачивается на весь экран, а также получает фокус.
vbNormalNoFocus 4 Окно восстанавливает свое исходное положение и размер, но фокус не получает.
vbMinimizedNoFocus 6 Окно отображается в виде значка, но фокус не получает.

Примечания

  • Если функция Shell успешно запускает указанную программу, возвращается код (идентификатор) задачи запущенной программы (ID процесса в Диспетчере задач). Если функция Shell не может запустить указанную программу из кода VBA Excel, происходит ошибка.
  • Если в полном имени запускаемой программы содержатся пробелы, полное имя программы следует заключить в тройные кавычки (три пары двойных кавычек): """C:Program FilesПапка программыимя.exe""".
  • По умолчанию функция Shell запускает другие программы асинхронно. Это означает, что программа, запущенная с помощью команды Shell, может не завершиться до того, как будут выполнены операторы, следующие за функцией Shell.

Примеры

Пример 1
Запустим с помощью функции Shell программу Notepad++, отобразим идентификатор задачи в информационном окне MsgBox и сравним его с ID процесса в Диспетчере задач.

Используем в параметре pathname тройные кавычки (три пары двойных кавычек), так как полное имя файла содержит пробелы:

Sub Primer1()

Dim myTest

    myTest = Shell(«»«C:Program Files (x86)Notepad++notepad++.exe»«», vbNormalFocus)

MsgBox myTest

End Sub

ID процесса в информационном окне MsgBox:

ID процесса в информационном окне MsgBox

ID процесса в Диспетчере задач:

ID процесса в Диспетчере задач

Пример 2
Запуск проводника Windows из кода VBA Excel с помощью функции Shell.

Обе строки открывают окно проводника Windows с набором дисков и папок по умолчанию:

Shell «C:Windowsexplorer.exe», vbNormalFocus

Shell «explorer», vbNormalFocus

Обе строки открывают папку «Текущая папка»:

Shell «C:Windowsexplorer.exe C:UsersPublicТекущая папка», vbNormalFocus

Shell «explorer C:UsersPublicТекущая папка», vbNormalFocus

Пример 3
Запуск командной строки из кода VBA Excel с помощью функции Shell.

Обе строки запускают программу cmd и открывают окно командной строки:

Shell «C:WindowsSystem32cmd.exe», vbNormalFocus

Shell «cmd», vbNormalFocus

Записываем строку «Большой привет!» в файл «C:Тестовая папкаtest1.txt» (если файл не существует, от будет создан):

Shell «cmd /c echo Большой привет!>»«C:Тестовая папкаtest1.txt»«», vbHide

Здесь полное имя файла является параметром программы cmd, поэтому, если оно содержит пробелы, оно заключается в две пары двойных кавычек, а не в три, как параметр pathname функции Shell.

Константа vbHide используется для того, чтобы при выполнении команды не мелькало окно командной строки.

Параметр «/c» программы cmd указывает, что после выполнения команды программа завершает работу и окно командной строки закрывается. Чтобы программа cmd после выполнения команды продолжила работу и ее окно осталось открытым, вместо параметра «/c» следует указать параметр «/k» и заменить константу vbHide на константу, не скрывающую окно.

Копируем файл «C:Тестовая папкаtest1.txt» в файл «C:Тестовая папкаtest2.txt»:

Shell «cmd /c copy ««C:Тестовая папкаtest1.txt»» ««C:Тестовая папкаtest2.txt»«», vbHide

Смотрите как открывать из кода VBA Excel файлы других приложений и интернет-сайты.


 

Доброго времени суток всем.
Обращаюсь за помощью. Хотелось бы сделать в excel такую функцию чтобы при нажатии кнопки, запускалась программа google earth. Проблема в том что не знаю как прописать команду на запуск приложения.

Адрес расположения.
c:Program Files (x86)GoogleGoogle Earthclientgoogleearth.exe

Заранее спасибо

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

читакм справку VBA по функции Shell

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

 

Ооо, круто.

sub google()
Dim go
go= Shell(«c:Program Files (x86)GoogleGoogle Earthclientgoogleearth.exe», 1)

end sub

Заработало супер! Спасибо.
Не сочтите за наглость, а почему shell не срабатывает на запуск файла. У меня есть файл в corele. Записываю команду

sub corel()
Dim co
co= Shell(«dcorelКаталог.cdr», 1)

end sub

А он выдает ошибку? Спасибо

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

#5

08.05.2013 13:34:17

т.е. совет почитать справку проигнорировали?  :)

Цитата
Runs an executable program

«файл корела» не является исполняемой программой.

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

 

О да, я помню эту тему. Так хотелось сразу закидывать на эту форму метки, но я так и смог реализовать идею.
Но как использовать
With UserForm1
.WebBrowser1.Navigate «http://maps.google.ru/»
под запуск файла?

 

Шарафеев Дамир

Пользователь

Сообщений: 76
Регистрация: 01.01.1970

#8

08.05.2013 14:25:42

Цитата
«файл корела» не является исполняемой программой.

Честно, пробежался и сделал! С английским дружу на 3 с —  :D

 

Казанский

Пользователь

Сообщений: 8839
Регистрация: 11.01.2013

#9

08.05.2013 15:06:47

?

Код
shell "cmd /c d:corelКаталог.cdr",vbHide
 

Шарафеев Дамир

Пользователь

Сообщений: 76
Регистрация: 01.01.1970

#10

08.05.2013 15:25:50

Во, круто

Код
sub corel() 
Dim co 
co=Shell("cmd /c "dcorelКаталог.cdr", 0) 
end sub

Спасибо огромнейшее!!! Это то что надо.

Всем спасибо за помощь.

 

Филипп

Пользователь

Сообщений: 27
Регистрация: 06.01.2013

#11

10.05.2013 17:34:30

Цитата
Юрий М пишет:  Было с картой (см. файл)

как в строку поиска вставить данные из ячеийки и нажать энтер?
пытаюсь с помощью SendKeys, но к сожалению не получается  :(

 

anvg

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

#12

11.05.2013 08:16:57

Цитата
пытаюсь с помощью SendKeys, но к сожалению не получается

А зачем SendKeys?

Код
.WebBrowser1.Navigate "https://maps.google.ru/maps?q=Санкт-Петербург,+Зимний+дворец"

Так что конструируйте адрес на maps.google.ru и значение в ячейке

 

Филипп

Пользователь

Сообщений: 27
Регистрация: 06.01.2013

 

Филипп

Пользователь

Сообщений: 27
Регистрация: 06.01.2013

с этим разобрался .WebBrowser1.Navigate «https://maps.google.ru/maps?q=Санкт-Петербург,+Зимний+дворец»

http://www.gdeetotdom.ru/map

а на этом сайте, к сожалению, в строку поиска не знаю как вставить текст.

 

gtz

Пользователь

Сообщений: 36
Регистрация: 16.12.2016

#15

14.02.2018 10:33:14

Юрий М
круто =)

Что такое всё?

Visual Basic for Applications (VBA) is a frequently used utility for Microsoft applications — including Microsoft Excel, Office, PowerPoint, Word, and Publisher. As VBA is a fairly complicated language to learn, much has been written about it and its capabilities (and if you want to learn more about VBA and Excel, you can read about it here).

One of the most basic tasks you can use VBA for is to open and manipulate files, such as an Excel file. VBA open files will open the Excel file — from there you can control how it is read and written. Commonly, you would use VBA code to open the file, and then use Excel VBA macros to write to the file. 

Let’s take a deeper look into how VBA open files can be used with an Excel Workbook.

What is VBA Open Files and how does it work?

VBA is extremely similar to Visual Basic, a programming language used within the Microsoft ecosystem. It is used to create “macros.” A macro is a sequence of automated events which can fine-tune, optimize, automate, and improve your operations. The Excel VBA implementation can open files and run macros on them.

In Excel, you use VBA by inserting the code in the Visual Basic Editor. You can also choose the “Macro” button on the Developer Tab. From there, you will enter in code as though programming.

Before you start digging into VBA, you should have some understanding of programming. Programming means directing a computer to perform a certain sequence of events. Keep a few things in mind:

  • You should always test your programming thoroughly to make sure it does what you want it to do.
  • You should never implement your programming in a “live” environment with important data rather than test data.
  • You should save your work frequently and you should be prepared to restore both your programming and your data if needed.
Person wearing headphones looking at laptop screen and typing

Running the macros you program

When macros are created, they’re assigned to given keypresses. Sometimes this is a combination of keys, and sometimes it’s an extra mouse button. Regardless, they’re intended to set off an automated chain of events whenever you do the given action (whether it’s pressing a key on your keyboard, or a button on your mouse). You can also run a macro manually by selecting it.

So, when you run a macro, you have Microsoft Excel already open. The macro runs within Excel, and you will do all your VBA programming inside of that program. Likewise, you will do your Microsoft Word VBA programming inside of Microsoft Word.

Opening an Excel file with VBA

The first step to updating, modifying, and saving Excel files is to be able to open them. To open an Excel file with VBA you would program as follows:

Sub openworksheet()
	Workbooks.Open filename:= _ “filepath”
	End sub

The “sub” above is a lot like a function. It creates a small amount of code that is intended to take action. It begins with “Sub” and ends with “End Sub.”

In the above code, note that the italicized “filepath” references the full path of the workbook. Without the appropriate Workbooks.Open filename, you won’t be able to open the given file. You will also need the appropriate file type (Microsoft Excel, which is either XLS or XLSX) or the open method will fail.

Of course, the above assumes that you are always going to be opening the Workbook at the “filepath.” You might also want to open any file at all. You can create a macro that opens a dialog, through which you can select any file.

	Sub openworksheet()
	Dim Flocation as Variant
	Flocation = Application.GetOpenFileName()
	If Flocation <> false then 
	Workbooks.Open Filename:= Flocation
	End If
	End Sub

The above code prompts the user to give a file name. If the user does give a file name (the variable, Flocation is no longer false), then the program will open that file.

Also note that Flocation is just the name of the variable that’s being used. You could call it something else; in fact, you could even call it just “f.” All that’s important is that you don’t use a word that the code already uses, such as “Variant” or “Filename.”

You might also be wondering why this code is so important. After all, you can open your own files at any time. But you can bind it to a specific keypress, making it a macro. So, now, typing something like “F8” will automatically open the “open a file” dialog.

But once you’ve automatically opened a file, what’s next? Generally, opening the file is only the first step. Once you’ve opened the Excel file, you still need to be able to read and write to it.

Reading the Excel file

You’ve opened your Excel file. But what’s inside of it? Luckily for you, it’s pretty easy to start reading an Excel file once you’ve opened it with VBA.

First, you should know that when you open a file, it becomes the ActiveWorkbook, which can be referenced in code as “ActiveWorkbook.”

Let’s say you want to read the first cell of the book.

Dim contents As Integer
	contents = ActiveWorkbook.Range(“A1”).value

Now, that does assume that the cell is an Integer. You would need to change it to a String if you were reading a string, or a Date if you were reading a Date. Consequently, you need to be really familiar with the type of data you’re reading before you go any further.

Now, note that this is reading the contents of the cell into just a variable. That’s not displaying it. That’s not doing anything with it at all. If you wanted to see, perhaps, what the contents were, you would then type:

MsgBox contents

Alternatively, you could:

MsgBox ActiveWorkbook.Range(“A1”).value

Either of these options should display the value. But, of course, it’s a static value; it’s always going to display A1. So, you might need to code things a little more expressively if you’re trying to read the entirety of a document, or if you’re trying to transition one document to another.

Writing to the file

So, you have your workbook open through the power of VBA. But now you want to write to the file. Writing can be used in tandem with reading; once the Workbook is open you could do both. 

As an example, you could write a macro that would open a Workbook and copy one column to another column, by reading the data in the first column and then writing that data to the second column.

Similarly, you could write a macro that would open two Workbooks and copy data from one to another, and then save both Workbooks, and then close both Workbooks.

As mentioned, once you open a workbook with VBA, the workbook that you opened becomes the ActiveWorkbook. This also happens if you have created a new workbook within VBA.

You can then access its data through:

ActiveWorkbook.Sheets
ActiveWorbook.Cells

As an example, if you wanted to edit the cell at column 1, row 1, on Sheet 1, you would write as follows:

ActiveWorkbook.Sheets(“Sheet 1”).Cells(1,1).Value= “1”

If this is confusing, you can also use the “Range” field.

ActiveWorkbook.Sheets(“Sheet 1”).Range(“A1”).Value= “1”

The above would have the same result.  

Writing to a sheet can become very complex. Consider that, when you’re writing the macro system, you don’t know what data is in those cells. You only know their positions. You’re essentially writing to that position blindly.

Macros are frequently used to do things such as read CSV files and import that CSV information into a brand new Microsoft Excel workbook. But it takes a lot of time and a lot of testing to ensure that the data is going through correctly.

In the above case, you’re only altering range A1. But you could iterate through all the rows and columns of a workbook one by one if you were trying to fill it out line by line. As you learn more about Excel and VBA, you will learn more advanced methods of both reading and writing data.

Saving the Excel workbook file

Just like when you’re using Excel regularly, you still need to save your changes. If you have opened and changed a Workbook, save it before you close it. 

ActiveWorkbook.Save

You could even write a Macro that would save all your workbooks and close them, as follows:

For each workbook in Application.Workbooks
		workbook.Save
	Next workbook
		Application.Quit

The above code iterates through each Workbook saving it until it cannot find a Workbook anymore. Once it can no longer find a Workbook, it quits the application. This is very useful for those who want to shut down fast and have a lot of workbooks left to save.

Closing the selected file

Closing the file is just as easy as opening a workbook. In fact, it’s actually easier, because you don’t need to know the file name. VBA already knows which file it has opened.

To close the Excel file you would type:

ActiveWorkbook.Close

On the other hand, perhaps you wanted to close a specific Workbook. In that case, you would use the following:

Workbooks(“book.xlsx”).Close

This is under the assumption the book was called “book.xlsx”; you would replace the given name for your sheet. Once you have closed the Workbook, you will not be able to make any further modifications to it until you open it again.

Opening a Microsoft Excel workbook that is password protected

Sometimes you may have password-protected your workbooks. That goes into more complicated territory. Understandably, it’s not going to open if you just try to directly open it. 

But you can still open it with VBA.

Workbooks.Open(filename:= “filename”, Password:= “password”)

As you can see above, you just added the password directly into the macro. Now the file is going to open just fine.

But there’s a problem with the above, which (if you’re good with security) you already know. You just saved your password as plain text! 

Now, anyone with access to your computer could potentially open that file without knowing the password. And if you’ve been using that password for multiple files (a big no-no), they could be compromised, too.

So, VBA does provide a method of opening files that have a password. But it’s not a good method because of the above reasons. It means that your system could be compromised. If you just have a password to prevent outside intrusion (the file being sent somewhere else and opened by an outsider), this may not be a problem. But if you’re trying to protect your file internally as well as externally, it can be a major issue.

The alternative is to use the previous method of opening a file with a dialogue box. When you press a button (or otherwise launch your macro), you’ll be given a dialogue box, and you’ll be able to open whatever file you want. Your macro can then continue actions on the file after you have manually entered your password. 

Opening a read-only file

Some Microsoft Excel files don’t have a password when you open them. Instead, they are set to read-only. If they’re set to read-only, you’ll be able to open and read from them. But you won’t be able to actually write to them without a secondary password. 

ActiveWorkbook.Password = “password”

Above is the method that you would call after you’ve opened the book so that you can start to write to it. You wouldn’t include the password when opening the file, because you wouldn’t have been prompted for it then.

The benefits of using Excel VBA Open

VBA is used to automate routine, mundane tasks, such as copying large volumes of data from one book to another. Any time you’re finding yourself spending hours just copying and pasting data, or running fairly mundane calculations, a macro can help.

You can also use VBA to automate smaller tasks that you find use a lot of keypresses. If you find yourself frequently needing to open the same 10 Excel Workbooks at once, for instance, you can create a macro that will open all of them on a single keypress, and close them all, too.

While it may only save you a few minutes of time, those minutes of time add up.

Potential issues with Excel VBA Open

It’s possible to run into issues with VBA open. If you have a protected workbook, you won’t be able to open it without the password (as noted). If you don’t have the password, you aren’t going to be able to open the file.

If the selected file is read-only, you aren’t going to be able to write to it without the right permissions. If you don’t realize that the file is read-only, you could try writing to it only for the action to fail. 

And because you can’t always see what the macro is doing until you run it, you can potentially overwrite data or delete it altogether. This is why it’s always important to test your macros with test data before trying to implement it with live data.

But even so, Excel VBA open is a robust language. Most common activities with Workbooks (such as opening, closing, reading, writing, and saving) can be completed quite intuitively and often with a single line of code.

Learning more about Excel VBA

In the right hands, VBA is very powerful. If you have any automated, routine tasks in Excel, consider automating them with Excel VBA. Even better, once you learn the basics of VBA, you can also use it in other Microsoft applications such as Microsoft Word.

Still, powerful also means that mistakes can be made. Because VBA can open files and write to them, it’s also possible that it can overwrite data. This is why testing your programming is so important. 


Frequently Asked Questions:

Can a macro open a file?

The Excel Macro can be used to prompt a user to open a file or to open a specific file (given the entire filename). 

How do I open a text file in Excel VBA?

The VBA OpenTextFile method can be used to open a text file, just as the VBA Workbooks.Open method is used to open an Excel file.

How do I open a new workbook in VBA?

To open a new workbook in VBA, you would use the Workbooks.Add() VBA function. This function both creates a new workbook and prioritizes it as the active workbook.

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.

Хитрости »

22 Октябрь 2011              100198 просмотров


Как запустить файл с включенными макросами?

В данной статье хочу описать вкратце способ, как можно запустить какой-то файл Excel с разрешенными макросами. Зачем это надо: бывают ситуации, когда Вы высылаете файл с макросами и хотите, чтобы его открывали только с разрешенными макросами, т.к. без них он бесполезен (как правило через макросы выполняются некие операции при работе с файлом). В принципе есть способы заставить пользователя работать с файлом только при включенных макросах. Самый простой (способ 1) — это заставить его именно разрешить их выполнение, прежде чем начать работу с файлом.

Вариант 1:
Самый простой и легко исполняемый способ. Создаете в нужной книге новый лист. Называете его «WARNING». На листе мы пишем инструкцию по действиям пользователя для включения макросов. Что-то типа:
Для работы с файлом требуется разрешить макросы!
Excel 2003: Сервис- Безопасность- Уровень макросов «Низкий»
Excel 2007: Меню- Параметры Excel- Центр управления безопасностью- Параметры центра управления безопасностью- Параметры макросов- Разрешить все макросы;
Excel 2010: Файл- Параметры- Центр управления безопасностью- Параметры центра управления безопасностью- Параметры макросов- Разрешить все макросы.
И скрываем все листы в книге, кроме листа «WARNING». Теперь в остается дело за малым: в модуль книги вставляете следующий код:

'Данная процедура скрывает перед закрытием книги все листы,
'кроме листа "WARNING"
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.ScreenUpdating = False
    Dim wsSh As Worksheet
    Sheets("WARNING").Visible = -1
    For Each wsSh In ThisWorkbook.Sheets
        If wsSh.Name <> "WARNING" Then wsSh.Visible = 2
    Next wsSh
    ThisWorkbook.Save
End Sub
'Данная процедура показывает перед открытием книги все листы,
'кроме листа "WARNING"
Private Sub Workbook_Open()
    Dim wsSh As Worksheet
    For Each wsSh In ThisWorkbook.Sheets
        wsSh.Visible = -1
    Next wsSh
    ThisWorkbook.Sheets("WARNING").Visible = 2
End Sub

Из кода видно, что если макросы будут отключены, то код Workbook_Open не будет выполнен. Следовательно пользователь увидит только лист «WARNING», на котором у нас написаны инструкции по включению макросов, которые ему в любом случае придется выполнить, если есть желание работать с файлом.


Вариант 2:
Этот способ подразумевает создание отдельного файла, который будет запускать файл Excel. Я предоставлю на выбор либо скрипт VBS, либо созданный мной файл EXE. В чем прелесть. При использовании данного способа совершенно неважно запущен ли уже у пользователя Excel или нет, разрешены ли макросы. Скрипт или EXE сам все запустит и разрешит.
Что такое скрипт VBS? Это обычный текстовый файл, сохраненный с расширением VBS. Такой файл распознается операционной системой как исполняемый и код, расположенный в нем, запускается при двойном щелчке на файле. Чтобы создать такой файл необходимо: создать обычный текстовый файл. Открыть его. Записать в него текст:

test
Sub test() 
    Dim objXL
    Dim Secur
    Set objXL = CreateObject("Excel.Application") 
    objXL.Visible = TRUE
    secur = objXL.AutomationSecurity
    objXL.AutomationSecurity = 1
    objXL.Workbooks.Open replace(Wscript.ScriptFullName,".vbs",".xls"),,,,"4321"
    objXL.AutomationSecurity = secur
End Sub

Сохранить. Поменять расширение текстового файла с .txt на .vbs.
Если не отображается расширение:
Панель управленияСвойства папки(для Win 7 — Параметры папок)- вкладка Вид— Снять галочку с «Скрывать расширение для зарегистрированных типов файлов»
Скрипт запускает файл Excel, имя которого совпадает с именем скрипта и расположенного в той же папке. В примере к статье это файл «Test». Таким образом Вы можете давать любое имя файлу Excel и файлу скрипта, лишь бы они совпадали. Т.е. назвав скрипт «Run», Вы должны будете и файл Excel назвать так же — «Run». В приведенном коде так же есть возможность указать пароль для открытия файла(в тексте скрипта это пароль 4321, но установить можно любой через свойства файла). Как установить пароль я описывал в этой статье: Как удалить книгу из самой себя. Пароль как правило устанавливается для того, чтобы при попытке запустить файл Excel без скрипта был запрошен пароль. Т.е. без скрипта файлом не воспользоваться. Есть и ложка дегтя — после открытия файла пароль может удалить любой, кто его открыл.
Плюсы использования скрипта:

  • пользователь совершает минимум действий
  • макросы разрешены как ни крутись

Минусы:

  • необходимость создания отдельного файла и привязка к имени
  • возможность подсмотреть пароль к файлу, просто сменив расширение файла-скрипта на .txt
  • возможность сменить/снять пароль к файлу после его открытия скриптом(можно избежать, внеся некоторый код в файл. Например сохранять только с нужным паролем). В примере пароль к файлу: 4321

Файл EXE. Долго пояснять не буду. Основные моменты все те же, что и со скриптом, т.к. в принципе это одно и то же, за исключением того, что код файла EXE нельзя подсмотреть, просто сменив расширение. А это значит, что и пароль к файлу подсмотреть тоже не получится(без использования специальных навыков и программ). Создается такой файл в специальной программной среде: С++, VisualBasic, Delphi и т.п. Основной минус: нельзя поменять пароль к файлу, не скомпилировав новый файл EXE. Т.е. если планируете использовать не с одним файлом, то надо всем им давать один и то же пароль, либо вообще не устанавливать пароль на открытие.

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

  Run_Wit_Macro.zip (28,1 KiB, 3 920 скачиваний)

Также см.:
Почему не работает макрос?
Управление безопасностью макросов


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

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


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



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

Понравилась статья? Поделить с друзьями:
  • Excel vba запустить макрос при открытии
  • Excel vba запуск макроса по кнопке
  • Excel vba запуск автоматически
  • Excel vba запросы к таблице
  • Excel vba запрос к sql server