In Excel VBA, use ThisWorkbook.Name for the name of the workbook containing the macro, or ActiveWorkbook.Name for the workbook currently active in Excel. To get only the filename from a full path, such as C:\Reports\Summary.xlsx, extract the text after the final backslash; the example below also handles forward slashes.
Private Function FileNameFromPath(ByVal fullPath As String) As String
Dim separatorPosition As Long
' Use whichever kind of slash appears last in the path.
separatorPosition = InStrRev(fullPath, "\")
If InStrRev(fullPath, "/") > separatorPosition Then
separatorPosition = InStrRev(fullPath, "/")
End If
FileNameFromPath = Mid$(fullPath, separatorPosition + 1)
End Function
The function returns the final path component, including its extension. For example, it returns Summary.xlsx from C:\Reports\Summary.xlsx. The right method depends on whether you need an open workbook’s name, a full path, or the name of a file the user selects.
Which file name do you need?
“Get the file name” can refer to several different values. VBA makes these distinctions useful because a filename alone is not enough to identify a file if other folders contain files with the same name.
- Name: The workbook’s name, usually with its extension, such as
Budget.xlsm. - Path: The folder containing a saved workbook, such as
C:\Reports. - FullName: The workbook’s full location and name, such as
C:\Reports\Budget.xlsm. - Base name: The name without its extension, such as
Budget.
Choose the value that fits the task. Displaying a workbook label may require only Name. Opening a related file or writing a sibling file usually requires the folder path as well. If you store only a filename, remember that it does not reveal which folder the file is in.
Get the name of an open workbook
Excel’s Workbook object exposes the Name, Path, and FullName properties. Use ThisWorkbook when you mean the workbook that contains the VBA code. Use ActiveWorkbook when you mean the workbook the user has selected at that moment. These are not necessarily the same: a macro stored in a personal macro workbook or an add-in can operate on another active workbook.
This short macro prints both names to the Immediate window in the Visual Basic Editor. To open that window, press Ctrl+G in the editor on Windows. On Mac, use the Visual Basic Editor’s View menu to show the Immediate window. Save a copy of the workbook before running a macro; VBA changes cannot be undone with Ctrl+Z.
Public Sub ShowWorkbookNames()
Dim macroBookName As String
Dim activeBookName As String
' Identify the workbook containing this code and the active workbook.
macroBookName = ThisWorkbook.Name
If Not ActiveWorkbook Is Nothing Then
activeBookName = ActiveWorkbook.Name
Debug.Print "ThisWorkbook: " & macroBookName
Debug.Print "ActiveWorkbook: " & activeBookName
End If
End Sub
If both references point to the same workbook, their names match. If the code is in one workbook and another workbook is active, they can differ. For automation that must always target the file containing the code, prefer ThisWorkbook rather than relying on whichever workbook happens to be active.
Get the full path and handle unsaved workbooks
For a saved workbook, ThisWorkbook.FullName returns its full location and filename, while ThisWorkbook.Path returns the folder location. ThisWorkbook.Name returns only the workbook name. These properties refer to the workbook containing the code; use ActiveWorkbook instead if the intended target is the active workbook.
A new workbook that has not yet been saved has no folder path. In that situation, Path is an empty string, so code that combines the path with another filename can create an incomplete location. Check for this before using the path. Also distinguish an empty path from a workbook saved at a location: a workbook’s name may exist before its first save, but that does not mean it has a usable disk location.
One safe pattern is to test the path before building a file location. If the path is empty, ask the user to save the workbook or choose a different destination rather than assuming a default folder. A workbook saved to a network location can have a longer path than a local file, but the same properties are used.
Extract a filename from a full path
The FileNameFromPath helper in the opening example takes a path as text and returns the part after the last slash. Pass it a value such as ThisWorkbook.FullName to get the current macro workbook’s filename. It handles both Windows backslashes and forward slashes, which can appear in paths supplied by other systems.
For an existing local file, VBA’s Dir function can also return the final filename from a full path. For example, Dir$("C:\Reports\Summary.xlsx") returns Summary.xlsx when that file exists. The helper approach is more suitable when you simply need to parse a path string, even if you do not want to check whether the file exists. Dir is also used to search for files, and its search state can affect repeated calls, so avoid treating it as a general-purpose text parser in code that is enumerating a folder.
To remove an extension, locate the final period in the extracted filename and take the text before it. Be careful with names that contain multiple periods: Quarter.4.Report.xlsx has a base name of Quarter.4.Report, not Quarter. A filename can also have no extension, so code should check that a period was found before shortening the text. For more involved path manipulation, the Windows FileSystemObject provides methods such as GetFileName and GetBaseName; it can be created through VBA without adding a reference by using late binding.
Let the user choose a file
If the user needs to select a file, Application.GetOpenFilename displays Excel’s file-selection dialog and returns the selected path as text. It does not open the selected workbook. If the user cancels, it returns the Boolean value False, so check for cancellation before converting the result to a string or extracting a filename.
The following macro selects an Excel workbook and displays just its filename. It uses the helper function from the opening example, so place both procedures in the same standard VBA module. Save a copy of the workbook before running a macro; macro actions cannot be reversed with Ctrl+Z.
Public Sub ChooseWorkbookAndShowName()
Dim selectedFile As Variant
Dim selectedName As String
' Ask for a workbook; cancellation returns Boolean False.
selectedFile = Application.GetOpenFilename( _
FileFilter:="Excel files (*.xls*),*.xls*", _
Title:="Select a workbook")
If VarType(selectedFile) = vbBoolean Then Exit Sub
selectedName = FileNameFromPath(CStr(selectedFile))
MsgBox selectedName, vbInformation, "Selected file"
End Sub
The filter limits the dialog to matching Excel file extensions, but it does not guarantee that a selected file is valid or that VBA can open it. If you need to work with the selected workbook afterward, use a separate step to open it and handle possible errors, such as a file being moved or access being denied between selection and opening.
Get the folder, extension, or a sibling filename
When you need to create a file beside the current workbook, combine its folder with a new filename. First verify that the workbook has been saved and that Path is not empty. Then add the Windows path separator and the new name. This is different from using FullName, which already includes the existing workbook’s filename.
It is often useful to preserve the original extension when reporting a workbook name, because .xlsx, .xlsm, and other extensions indicate different file formats. A macro-enabled workbook should generally remain in a macro-enabled format if it is saved with VBA code; changing the extension by editing a text string does not convert the workbook’s contents or format.
For a file path supplied by an external source, avoid assuming that every path uses a particular separator or that every filename has an extension. Paths can be malformed, empty, or point to a folder rather than a file. Validate the input for the operation you plan to perform, and use the full path when different directories could contain duplicate names.
Common problems and practical safeguards
- Using the wrong workbook reference:
ActiveWorkbookcan change as the user switches windows. UseThisWorkbookfor the workbook containing the code. - Expecting a path from
Name: The name property omits the folder. UseFullNamewhen the complete location is needed. - Handling cancellation as text: A cancelled
GetOpenFilenamecall returns BooleanFalse. Test that result before passing it to a string function. - Assuming a new workbook is saved: An unsaved workbook has an empty
Path. Check for it before constructing a location. - Confusing a filename with an existing file: Parsing a string does not prove that a file exists. Check or open the file separately when existence matters.
Macros may also be blocked by Excel’s macro security settings or by an organization’s policy. Only enable or run VBA from workbooks you trust. On Windows, the Visual Basic Editor is available with Alt+F11; on Mac, the editor can be opened from Excel’s Tools menu, though keyboard shortcuts can vary with macOS settings. Excel for the web does not run VBA macros, so use desktop Excel for these procedures.
Where to put and run the VBA
In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor. Choose Insert > Module, paste the code into the new standard module, and run a public macro from the editor or Excel’s macro interface. If the workbook must retain the code, save it in a macro-enabled format such as .xlsm. Saving as a macro-free format can remove the VBA project.
On a Mac, open the Visual Basic Editor from Excel’s Tools menu and insert a standard module in the same way. The file picker and VBA object model are available in desktop Excel, but some platform-specific paths or dialog details can differ. Excel for the web can display a macro-enabled workbook, but it cannot run or edit VBA macros. Before running any macro that changes files or workbook contents, save a separate copy: Ctrl+Z does not undo VBA operations.
Frequently Asked Questions
How do I get the current Excel workbook’s filename in VBA?
Use ThisWorkbook.Name for the workbook containing the code. Use ActiveWorkbook.Name only when you specifically want the workbook currently active in Excel.
How do I get a filename without the folder path?
Use Workbook.Name for an open workbook, or pass a full path to a helper that returns the text after the last slash. For an existing local file, Dir can return the final filename component.
How do I get the full file path in Excel VBA?
Use ThisWorkbook.FullName for the workbook containing the macro. It includes both the folder location and the workbook name. Check ThisWorkbook.Path first if the workbook may not have been saved.
What is the difference between ThisWorkbook and ActiveWorkbook?ThisWorkbook is the workbook that stores the running VBA code. ActiveWorkbook is the workbook currently active in the Excel window. They can refer to different workbooks.
How can I get the selected file’s name from a file dialog?
Use Application.GetOpenFilename, check whether its result is Boolean False because the user cancelled, and then extract the filename from the returned path. The dialog selects a file but does not open it.
Can VBA run in Excel for the web?
No. Excel for the web does not run VBA macros. Open the workbook in desktop Excel for Windows or Mac to use VBA.
Related
- Freeze Panes in Excel: Keep Rows and Columns Visible
- Find Duplicates in Excel: A Practical Step-by-Step Guide
- How to Find External Links in Excel and Check Their Sources
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel Macros in Google Sheets: What You Can and Can’t DoNo—Excel macros written in VBA do not run in Google Sheets. You can usually open or import an…
- VBA Loop Statements: Types, Examples, and When to Use ThemA VBA loop statement repeats a block of code, either for a set number of passes or while…
- Excel VBA: How to Copy a UserForm to Another WorkbookTo copy an Excel VBA UserForm to another workbook, export the form from the source workbook’s VBA project…
- Excel Range Find VBA: Search Cells ReliablyIn Excel VBA, use the Range.Find method to search a specified range; check whether it returned a cell…
- Excel VBA Hex: Convert Numbers and ColorsIn Excel VBA, use the Hex function to turn a number into its hexadecimal text representation: for example,…
- Excel VBA: Delete a Row from a TableTo delete a data row from an Excel table with VBA, use the table’s ListRows collection: for example,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.