Vba как открыть файл excel с макросом

Открытие книги Excel из кода VBA. Проверка существования книги. Создание новой книги, обращение к открытой книге и ее закрытие. Методы Open, Add и Close.

Открытие существующей книги

Существующая книга открывается из кода VBA Excel с помощью метода Open:

Workbooks.Open Filename:=«D:test1.xls»

или

Workbooks.Open («D:test1.xls»)

В кавычках указывается полный путь к открываемому файлу Excel. Если такой файл не существует, произойдет ошибка.

Проверка существования файла

Проверить существование файла можно с помощью функции Dir. Проверка существования книги Excel:

If Dir(«D:test1.xls») = «» Then

    MsgBox «Файл не существует»

Else

    MsgBox «Файл существует»

End If

Или, если файл (книга Excel) существует, можно сразу его открыть:

If Dir(«D:test1.xls») = «» Then

    MsgBox «Файл не существует»

Else

    Workbooks.Open Filename:=«D:test1.xls»

End If

Создание новой книги

Новая рабочая книга Excel создается в VBA с помощью метода Add:

Созданную книгу, если она не будет использоваться как временная, лучше сразу сохранить:

Workbooks.Add

ActiveWorkbook.SaveAs Filename:=«D:test2.xls»

В кавычках указывается полный путь сохраняемого файла Excel, включая присваиваемое имя, в примере — это «test2.xls».

Обращение к открытой книге

Обращение к активной книге:

Обращение к книге с выполняемым кодом:

Обращение к книге по имени:

Workbooks(«test1.xls»)

Workbooks(«test2.xls»)

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

Открытая рабочая книга закрывается из кода VBA Excel с помощью метода Close:

Workbooks(«test1.xlsx»).Close

Если закрываемая книга редактировалась, а внесенные изменения не были сохранены, тогда при ее закрытии Excel отобразит диалоговое окно с вопросом: Вы хотите сохранить изменения в файле test1.xlsx? Чтобы файл был закрыт без сохранения изменений и вывода диалогового окна, можно воспользоваться параметром метода Close — SaveChanges:

Workbooks(«test1.xlsx»).Close  SaveChanges:=False

или

Workbooks(«test1.xlsx»).Close  (False)

Закрыть книгу Excel из кода VBA с сохранением внесенных изменений можно также с помощью параметра SaveChanges:

Workbooks(«test1.xlsx»).Close  SaveChanges:=True

или

Workbooks(«test1.xlsx»).Close (True)


Фразы для контекстного поиска: открыть книгу, открытие книги, создать книгу, создание книги, закрыть книгу, закрытие книги, открыть файл Excel, открытие файла Excel, существование книги, обратиться к открытой книге.


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-файлов, или подгрузка доп.данных из внешнего файла решается достаточно просто: создается объект Excel, который можно скрыть визуально, затем открывается необходимый файл и выполняются нужные действия. Просто приведу несколько примеров.

Открытие файла Excel

Set objExcel = New Excel.Application
objExcel.Visible = False
Set wb = objExcel.Workbooks.Open(fname)
Set ws = wb.Sheets(1)

В первой строке запускаем новый Excel, затем делаем его невидимым, в 3-й строке открываем файл fname. В последней строке получаем первый лист открытого excel-кого файла.

Альтернативный вариант открытия файла

Set objExcel = New Excel.Application
Set wb = objExcel.Workbooks
wb.Open fname, local:=True
Set ws = wb.Item(1).ActiveSheet

При открытии файла можно использовать доп.параметры (приведу некоторые):

UpdateLinks — обновлять или нет внешние ссылки при открытии файла;
ReadOnly — открытие в режиме только для чтения;
Format — используемый при открытии разделитель (1 — символ tab, 2 — запятые, 3 — пробелы, 4 — точка с запятой, 5 — без разделителя, 6 — пользовательский разделитель, заданный в Delimiter);
Delimiter — пользовательский разделитель (в случае, если Format = 6);
Origin — тип операционной системы (xlMacintosh, xlWindows или xlMSDOS);
Local — использование в Excel языка такого же, как в открываемом файле.

Теперь можно выполнять какие-то действия с открытым файлом, просто обращаясь через wb и ws.

ws.Cells(1, 1).Value = "Test"
ws.Cells(1, 1).Font.Size = 18 ' Поменять размер шрифта
ws.Cells(1, 1).HorizontalAlignment = xlCenter ' 

Записать книгу и закрыть

wb.Save ' Записать с тем же именем
wb.SaveAs Filename:="имя_нового_файла", FileFormat:=xlOpenXMLWorkbookMacroEnabled ' Записать в новый файл
wb.Close ' Закрыть книгу

Для записи текущей книги (где находится макрос), можно использовать:

ActiveWorkbook.SaveAs 

Чтобы сохранить или перезаписать книгу Excel без вопросов, можно применить такой вариант:

Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="c:Temp001.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = True

У метода SaveAs есть несколько параметров сохранения, с ними можно ознакомиться на сайте Microsoft.

Если нужно, можно закрыть книгу Excel без сохранения изменений таким образом:

wb.Close False

Sub макрос()

    Dim FN As String, bk As Workbook

            ‘ Записываем в переменную ‘FN’ полное имя (путь + имя) эксель-файла.
        ‘ Переменную не обязательно использовать, можно подставить полное имя прямо в код.
    FN = «C:UsersUserDesktopКнига1.xlsb»

        ‘ Открываем эксель-файл и присваиваем ему имя ‘bk’.
        ‘ Далее в макросе будем обращаться к файлу по имени ‘bk’.
    Set bk = Workbooks.Open(FN)

        ‘ Здесь вы делаете манипуляции с эксель-файлом.
        ‘ Для этого обращайтесь к файлу по имени ‘bk’.

        ‘ Сохранение эксель-файла.
    bk.Save

        ‘ Закрытие эксель-файла без сохранения.
        ‘ Ранее мы уже сохранили, но иногда бывают ситуации, что мы ничего не делаем,
        ‘ но эксель предлагает нам сохранить.
    bk.Close SaveChanges:=False

End Sub

[свернуть]

Skip to content

На чтение 2 мин. Просмотров 5.1k.

Что делает макрос: Этот макрос открывает диалоговое окно, в котором отображаются только excel-файлы, тем самым позволяет открыть конкретную книгу

Содержание

  1. Как макрос работает
  2. Код макроса
  3. Как работает этот код
  4. Как использовать

Как макрос работает

Данный макрос открывает диалоговое окно, как показано на рис, что позволяет пользователю просматривать и открывать файл Excel.

Как открыть конкретную книгу в Excel

Код макроса

Sub Macro7()
'Шаг 1: Определяем переменную.
Dim FName As Variant
'Шаг 2: Метод GetOpenFilename активизирует диалоговое окно.
FName = Application.GetOpenFilename( _
'a – определяем тип файла
FileFilter:="Excel Workbooks,*.xl*", _
'b – заголовок окна
Title:="Выбери файл, который надо открыть", _
'c – множественный выбор
MultiSelect:=False)
'Шаг 3: Если был выбран файл, открыть его!
If FName <> False Then
Workbooks.Open Filename:=FName
End If
End Sub

Как работает этот код

  1. Первое, что делаем — объявляем переменную типа Variant, будет содержать Имя файла, который пользователь выберет. FName — имя нашей переменной.
  2. На шаге 2 мы используем метод GetOpenFilename, чтобы вызвать диалоговое окно, которое позволяет просмотреть содержимое папки и выбрать нужный нам файл. Метод
    GetOpenFilename поддерживает несколько настраиваемых параметров:
    a. FileFilter параметр позволяет указать Тип файла, который мы ищем.
    b. Title позволяет изменить заголовок, который отображается в верхней части диалогового окна.
    c. MultiSelect — параметр множественный выбор позволяет ограничить выбор в один файл.
  3. Если пользователь выбирает файл из диалогового окна, переменная FName берёт Имя файла, который выбрали. Если переменная не пустая, мы используем метод Open из книг
    объекта, чтобы открыть файл.

Как использовать

Для реализации этого макроса, вы можете скопировать и вставить его в стандартный модуль:

  1. Активируйте редактор Visual Basic, нажав ALT + F11.
  2. Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
  3. Выберите Insert➜Module.
  4. Введите или вставьте код во вновь созданном модуле.
  5. По желанию, можно назначить макрос к кнопке, чтобы открыть файл.

Понравилась статья? Поделить с друзьями:
  • Vba для excel функция поиск
  • Vba для word если ошибка
  • Vba для excel фильтр
  • Vba для excel удалить пустые строки
  • Vba для excel ссылка на ячейку