To get the file name of the currently active workbook in VBA, use the ThisWorkbook.Name property for the file containing the code, or ActiveWorkbook.Name for the file currently in focus. For example, the line MsgBox ActiveWorkbook.Name will display a popup showing the name of the open Excel file including its extension.
Retrieving a file name is a fundamental task in Excel automation. Whether you are building a dynamic reporting tool that needs to reference its own name in a cell, or creating a macro that saves copies of files with a timestamped suffix, knowing how to capture the filename is the first step. Depending on your goal, you may need just the name (e.g., "Report.xlsx"), the full path (e.g., "C:\Documents\Report.xlsx"), or the name without the file extension (e.g., "Report"). VBA provides several built-in properties and functions to handle these variations.
What You'll Need
- Microsoft Excel installed on a Windows or macOS computer.
- The Developer tab enabled in the Excel Ribbon (if not visible, right-click any tab and select Customize the Ribbon, then check the Developer box).
- An Excel workbook that has been saved to a drive (unsaved workbooks do not have a file path).
- Basic familiarity with opening the Visual Basic Editor (VBE).
Step-by-Step
- Open the Visual Basic Editor: Open your Excel workbook. Press
Alt + F11on your keyboard to launch the VBA Editor. Alternatively, go to the Developer tab and click the Visual Basic button. - Insert a New Module: In the Project Explorer window on the left, right-click on your workbook name (e.g., VBAProject (Book1)). Select Insert > Module. This creates a blank space where you can write your code.
- Choose Your Method: Depending on what information you need, enter one of the following code blocks into the module window.
- Option A: Get the Basic File Name: If you only need the name of the file including the extension, use this code:
Sub GetFileName() Dim fileName As String fileName = ActiveWorkbook.Name MsgBox "The file name is: " & fileName End SubThis is the simplest method and works for any workbook currently active in the Excel session. - Option B: Get the Full File Path: If you need the folder location and the filename for saving or linking purposes, use the
FullNameproperty:Sub GetFullFilePath() Dim fullPath As String fullPath = ActiveWorkbook.FullName MsgBox "The full path is: " & fullPath End Sub - Option C: Get the File Name Without Extension: VBA does not have a single property for "name without extension," so you must use the
LeftandInStrRevfunctions to strip the extension away. Use this logic:Sub GetFileNameNoExtension() Dim fullFileName As String Dim cleanName As String fullFileName = ActiveWorkbook.Name cleanName = Left(fullFileName, InStrRev(fullFileName, ".") - 1) MsgBox "The name without extension is: " & cleanName End SubTheInStrRevfunction searches for the last period in the filename, and theLeftfunction keeps everything to the left of that point. - Run the Macro: To test the code, click inside the subroutine you wrote and press
F5, or return to Excel, go to the Developer tab, click Macros, select your macro name, and click Run. - Writing the Name to a Cell: Instead of a MsgBox, you can output the result directly into a worksheet. Replace the
MsgBoxline withRange("A1").Value = fileNameto place the name in cell A1 of the active sheet.
Common Mistakes
One of the most frequent errors occurs when users attempt to get the FullName or Path of a workbook that has never been saved. If a workbook is a new "Book1" that exists only in RAM, the Path property will return an empty string. This often leads to errors when the code tries to concatenate that empty string with a folder name or filename, resulting in a file path that doesn't exist on the hard drive.
Another common mistake is confusing ThisWorkbook with ActiveWorkbook. ThisWorkbook always refers to the workbook where the VBA code is actually written. ActiveWorkbook refers to whichever workbook is currently on top of the screen. If your macro is stored in a "Personal.xlsb" file but you want the name of the data file you are processing, using ThisWorkbook will incorrectly give you the name of the Personal macro workbook instead of the data file.
Users also frequently forget that file extensions can vary. While most modern files end in .xlsx or .xlsm, some older files end in .xls. Using a hard-coded subtraction (like Left(name, Len(name) - 5)) to remove the extension will fail if the extension length changes. Always use InStrRev to find the actual position of the dot.
Tips
To make your code more robust, implement a check to see if the workbook has been saved before requesting the path. You can use a simple If statement: If ActiveWorkbook.Path = "" Then MsgBox "Please save the file first!". This prevents the macro from crashing or producing empty results.
If you are working with a large number of files in a loop, avoid using ActiveWorkbook. Instead, assign the workbook to a variable. For example, Dim wb As Workbook: Set wb = Workbooks.Open("C:\Test\File.xlsx"). Then, you can use wb.Name. This ensures that even if the user clicks another window while the macro is running, the code continues to reference the correct file.
For those needing to extract names from files that are not currently open in Excel, you can use the Dir() function. Dir("C:\MyFolder\*.xlsx") will return the name of the first Excel file found in that directory. This is highly efficient for batch processing files without having to open every single one of them first.
Troubleshooting
If your code returns an empty string for the path, the first thing to check is whether the file is saved. A file named "Book1" has no path until it is saved to a local or network drive. Save the file as an .xlsm (Macro-Enabled Workbook) and run the code again.
If you receive a "Run-time error 9: Subscript out of range," it usually means you are trying to reference a workbook by a specific name that is not currently open. Ensure that the workbook you are targeting is open in the same instance of Excel. If you are using Workbooks("FileName.xlsx"), make sure the extension is included and spelled exactly as it appears in the title bar.
If the InStrRev method for removing extensions causes a crash, check if the file has a dot in the folder path or if the filename itself contains multiple dots (e.g., "Report.v2.xlsx"). InStrRev is designed to find the last occurrence of the character, which is why it is safer than InStr, but if no dot exists at all, the subtraction - 1 will result in an invalid length for the Left function. You can wrap this in an If InStr(fullFileName, ".") > 0 Then block to ensure a dot exists before attempting to strip it.
Frequently Asked Questions
Can I get the file name without the extension using a formula instead of VBA?
Yes, but it is complex. You can use a combination of MID, FIND, and CELL("filename"). However, the CELL function only works after the file has been saved. VBA is generally more reliable for this task.
What is the difference between .Name and .FullName?
The .Name property returns only the filename and extension (e.g., "Budget.xlsx"). The .FullName property returns the complete absolute path including the drive letter, folders, filename, and extension (e.g., "C:\Users\Admin\Documents\Budget.xlsx").
Will this code work on a Mac?
Yes, the .Name and .FullName properties work on macOS. However, be aware that Mac file paths use colons or forward slashes instead of backslashes, so if you are manipulating the path string, your code may need adjustments for cross-platform compatibility.
How do I get the name of a sheet instead of the workbook?
To get the name of the current worksheet, use ActiveSheet.Name. This will return the name on the tab at the bottom of the Excel window, such as "Sheet1" or "January_Data".
Can I get the names of all open workbooks at once?
Yes, you can loop through the Workbooks collection. Use a For Each wb In Workbooks loop to iterate through every open file and print their names to the Immediate Window or a list in a worksheet.