How do I browse and open a file in VBA?

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.

How do I browse and open a file in VBA?

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.

How do I browse a file in Excel VBA?

Open an Excel file by using browse window with VBA code.
Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window..
Click Insert > Module, and paste the following macro in the Module Window..

Can you use a macro to open a file?

As a programmer, you're likely to come across many situations where other files need to be opened for reading, writing, or appending data. A macro can help you easily handle these files, and the Open method is your ticket.

How do you open a file in Excel macro?

Run a macro from the Developer tab.
Open the workbook that contains the macro..
On the Developer tab, in the Code group, click Macros..
In the Macro name box, click the macro that you want to run, and press the Run button..
You also have other choices: Options - Add a shortcut key, or a macro description..

How do I select a file path in VBA?

VBA Blogs: File Path Selector.
Dim DialogBox As FileDialog..
Set DialogBox = Application.FileDialog(msoFileDialogFilePicker) DialogBox.Title = "Select file for " & FileType. ... .
If DialogBox.SelectedItems.Count = 1 Then. path = DialogBox.SelectedItems(1).
End If. ThisWorkbook.Names("File_Path").RefersToRange.Value = path..