Открытие книги 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, существование книги, обратиться к открытой книге.
Задача по объединению данных из нескольких 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
In this Article
- Open a Workbook in VBA
- Open Workbook From Path
- Open Workbook – ActiveWorkbook
- Open Workbook and Assign to a Variable
- Workbook Open File Dialog
- Open New Workbook
- Open New Workbook To Variable
- Open Workbook Syntax
- Open Workbook Read-Only
- Open Password Protected Workbook
- Open Workbook Syntax Notes
- Close a Workbook in VBA
- Close Specific Workbook
- Close Active Workbook
- Close All Open Workbooks
- Close First Opened Workbook
- Close Without Saving
- Save and Close Without Prompt
- Other Workbook Open Examples
- Open Multiple New Workbooks
- Open All Excel Workbooks in a Folder
- Check if a Workbook is Open
- Workbook_Open Event
- Open Other Types of Files in VBA
- Open a Text file and Read its Contents
- Open a Text File and Append to it
- Opening a Word File and Writing to it
In this tutorial, you will learn how to use VBA to open and close Excel Workbooks and other types of Files in several ways.
VBA allows you to open or close files using the standard methods .Open and .Close.
If you want to learn how to check if a file exists before attempting to open the file, you can click on this link: VBA File Exists
Open a Workbook in VBA
Open Workbook From Path
If you know which file you want to open, you can specify its full path name in the function. Here is the code:
Workbooks.Open "C:VBA FolderSample file 1.xlsx"
This line of the code opens “Sample file 1” file from the “VBA Folder”.
Open Workbook – ActiveWorkbook
When you open a workbook, it automatically becomes the ActiveWorkbook. You can reference the newly opened workbook like so:
ActiveWorkbook.Save
When you reference a sheet or range and omit the workbook name, VBA will assume you are referring to the ActiveWorkbook:
Sheets("Sheet1").Name = "Input"
Open Workbook and Assign to a Variable
You can also open a workbook and assign it directly to an object variable. This procedure will open a workbook to the wb variable and then save the workbook.
Sub OpenWorkbookToVariable()
Dim wb As Workbook
Set wb = Workbooks.Open("C:VBA FolderSample file 1.xlsx")
wb.Save
End Sub
Assigning workbooks to variables when they open is the best way to keep track of your workbooks
Workbook Open File Dialog
You can also trigger the workbook Open File Dialog box. This allows the user to navigate to a file and open it:
Sub OpenWorkbook ()
Dim strFile As String
strFile = Application.GetOpenFilename()
Workbooks.Open (strFile)
End Sub
As you can see in Image 1, with this approach users can choose which file to open. The Open File Dialog Box can be heavily customized. You can default to a certain folder, choose which types of files are visible (ex. .xlsx only), and more. Read our tutorial on the Open File Dialog Box for detailed examples.
Open New Workbook
This line of code will open a new workbook:
Workbooks.Add
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Open New Workbook To Variable
This procedure will open a new workbook, assigning it to variable wb:
Sub OpenNewWorkbook()
Dim wb As Workbook
Set wb = Workbooks.Add
End Sub
Open Workbook Syntax
When you use Workbooks.Open you might notice that there are many options available when opening the workbook:
The Filename is required. All other arguments are optional – and you probably won’t need to know most of the other arguments. Here are the two most common:
Open Workbook Read-Only
When workbook is opened read-only, you can’t save over the original file. This prevents the file from being edited by the user.
Workbooks.Open "C:VBA FolderSample file 1.xlsx", , True
VBA Programming | Code Generator does work for you!
Open Password Protected Workbook
A workbook might be password-protected. Use this code to open the password-protected workbook:
Workbooks.Open "C:VBA FolderSample file 1.xlsx", , , "password"
Open Workbook Syntax Notes
Notice that in the image above, we included a parenthesis “(” to show the syntax. If you use parenthesis when working with Workbooks.Open, you must assign the workbook to a variable:
Sub OpenWB()
Dim wb As Workbook
Set wb = Workbooks.Open("C:VBA FolderSample file 1.xlsx", True, True)
End Sub
Close a Workbook in VBA
Close Specific Workbook
Similarly to opening a workbook, there are several ways to close a file. If you know which file you want to close, you can use the following code:
Workbooks.Close ("C:VBA FolderSample file 1.xlsx")
This line of code closes the file “Sample file 1” if it’s opened. If not, it will return an error, so you should take care of error handling.
Close Active Workbook
If you want to close the Workbook which is currently active, this line of code will enable you to do that:
ActiveWorkbook.Close
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Close All Open Workbooks
To close all open Workbooks, you can simply use this code:
Workbooks.Close
Close First Opened Workbook
This will close the first opened/created workbook:
Workbooks(1).Close
Replace 1 with 2 to close the second opened / created workbook and so on.
Close Without Saving
This will close a Workbook without saving and without showing the save prompt:
ActiveWorkbook.Close savechanges:=False
Save and Close Without Prompt
Similarly this will save and close a Workbook without showing the save prompt:
ActiveWorkbook.Close savechanges:=True
Note: There are several other ways to indicate whether to save or not save a Workbook and also whether to show prompts or not. This is discussed in more detail here.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Other Workbook Open Examples
Open Multiple New Workbooks
This procedure will open multiple new workbooks, assigning the new workbooks to an array:
Sub OpenMultipleNewWorkbooks()
Dim arrWb(3) As Workbook
Dim i As Integer
For i = 1 To 3
Set arrWb(i) = Workbooks.Add
Next i
End Sub
Open All Excel Workbooks in a Folder
This procedure will open all Excel Workbooks in a folder, using the Open File Dialog picker.
Sub OpenMultipleWorkbooksInFolder()
Dim wb As Workbook
Dim dlgFD As FileDialog
Dim strFolder As String
Dim strFileName As String
Set dlgFD = Application.FileDialog(msoFileDialogFolderPicker)
If dlgFD.Show = -1 Then
strFolder = dlgFD.SelectedItems(1) & Application.PathSeparator
strFileName = Dir(strFolder & "*.xls*")
Do While strFileName <> ""
Set wb = Workbooks.Open(strFolder & strFileName)
strFileName = Dir
Loop
End If
End Sub
Check if a Workbook is Open
This procedure will test if a workbook is open:
Sub TestByWorkbookName()
Dim wb As Workbook
For Each wb In Workbooks
If wb.Name = "New Microsoft Excel Worksheet.xls" Then
MsgBox "Found it"
Exit Sub 'call code here, we'll just exit for now
End If
Next
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook_Open Event
VBA Events are “triggers” that tell VBA to run certain code. You can set up workbook events for open, close, before save, after save and more.
Read our Workbook_Open Event tutorial to learn more about automatically running macros when a workbook is opened.
Open Other Types of Files in VBA
You can use the VBA to open other types of files with VBA – such as txt or Word files.
Open a Text file and Read its Contents
The VBA open method allows you to read or write to the file once you have opened it. To read the contents of a file, we can open the file for INPUT.
Sub OpenTextFile()
Dim strFile As String
Dim strBody As String
Dim intFile As Integer
strFile = "C:datatest.txt"
intFile = FreeFile
Open strFile For Input As intFile
strBody = Input(LOF(intFile), intFile)
'loop here through your text body and extract what you need
''some vba code here
Debug.Print strBody
Close intFile
End Sub
The code above will open the text file “test.txt” and then it will read the entire contents of the file to the strBody variable. Once you have extracted the file data into the strBody variable, you can use it for what you require. Using the Debug.Print command above enables us to see the contents of the strBody variable in the Immediate window in the VBE.
Open a Text File and Append to it
We can also open a text file in VBA, and then append to the bottom of the file using the Append method.
Sub AppendToTextFile()
Dim strFile As String
Dim strBody As String
Dim intFile As Integer
strFile = "C:datatest.txt"
intFile = FreeFile
Open strFile For Append As intFile
'add two lines to the bottom
Print #intFile, "This is an extra line of text at the bottom"
Print #intFile, "and this is another one"
'close the file
Close intFile
End Sub
The above code will open the text file and then append 2 lines of text to the bottom of the file using the #intFile variable (the # sign is the key!). The code then closes the file.
Opening a Word File and Writing to it
We can also use VBA in Excel to open a Word file.
Sub OpenWordFile()
Dim wApp As Object
Dim wDoc As Object
Set wApp = CreateObject("Word.Application")
Set wd = wApp.documents.Open("c:datatest.docx")
wApp.Visible = True
End Sub
This code will open a copy of Word, and then open the document test.docx.
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.
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.
To open a workbook using VBA, you need to use the “Workbook.Open” method and specify the path of the file (make sure to specify the full path to the workbook with name and extension file type). This method has a total of fifteen optional arguments which you can use to deal with different kinds of files.
In this tutorial, we will explore it in detail and look at an alternative method that you can use.
Steps to Open a Workbook using VBA
- To start the code, use the “Workbooks” object.
- Type a dot (.) after that and select the Open method from the list.
- Specify the file path in the first argument and make sure to enclose it in double quotation marks.
- In the end, run the code to open the workbook.
Sub vba_open_workbook()
Workbooks.Open "C:UsersDellDesktopmyFile.xlsx"
End Sub
Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook
Workbook.Open Syntax
Now it’s time to look at the syntax of the method that you just have used in the above example. As I mentioned, there are fifteen arguments that you can use:
expression.Open (FileName, UpdateLinks, _
ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, _
Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
You won’t be using all these arguments. But a few of them are quite important and could be useful for you in the real world.
Opening a Password Protected Workbook
If you want to open a workbook that is password-protected, in that case, you can specify the password with the password argument.
Here I have a workbook on the desktop that has the password “test123” and now I want to open it and unprotect it at the same time. Following is the code that I need to use.
Workbooks.Open "C:UsersDellDesktopmyFile.xlsx", , , Password:="test123"
Opening a Workbook as Read Only
When you open a workbook as read-only you can’t make changes to the same workbook, but you need to save a copy of it.
Workbooks.Open "C:UsersDellDesktopFolder1.xlsx", , True
Open All the Workbooks from a Folder
Sub vba_open_multiple_workbooks_folder()
Dim wb As Workbook
Dim strFolder As String
Dim strFile As String
strFolder = "C:UsersDellDesktopFolder"
strFile = Dir(strFolder & "*.xls*")
Do While strFile <> ""
Set wb = Workbooks.Open(strFolder & strFile)
strFile = Dir
Loop
End Sub
To use it as per your needs, make sure to change the folder path.
Sub vba_open_dialog()
Dim strFile As String
strFile = Application.GetOpenFilename()
Workbooks.Open (strFile)
End Sub
More on VBA Workbooks
VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)
- VBA Workbook