VBA Workbook Name Without Extension: Best Methods
In this article
To get the workbook name without the extension in VBA, the most reliable method is to use the Left and InStrRev functions to strip everything from the last period onwards. For example, the code Left(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, '.') - 1) will return only the filename, removing extensions like .xlsx, .xlsm, or .xlsb.
Understanding the ThisWorkbook.Name Property
In Excel VBA, the Workbook object possesses a Name property. This property returns a string that represents the filename of the workbook as it appears in the title bar of the Excel application. However, it is crucial to understand that the behavior of this property changes based on whether the file has been saved to a disk or exists only in memory as a new, unsaved document.
When a workbook is saved, the Name property includes the file extension (e.g., "Financial_Report.xlsm"). Because VBA does not have a built-in property like Workbook.BaseName (which exists in the FileSystemObject library), developers must manually parse the string to isolate the name. If the workbook has never been saved, the Name property typically returns a generic string such as "Book1", which contains no extension. Attempting to run a string-stripping function on a filename that has no period can result in a runtime error if the code is not designed to handle that specific scenario.
Implementing the InStrRev Method
The InStrRev function is the gold standard for this task because it searches for a character starting from the end of the string and moving backward. This is vital because some filenames may contain periods within the name itself (e.g., "Project_v1.2_Final.xlsx"). A standard InStr search would find the first period and cut the name too short, whereas InStrRev finds the actual extension delimiter.
To implement this correctly, follow these logical steps:
- Capture the full name of the workbook using
ThisWorkbook.Name. - Use
InStrRevto locate the position of the last dot (.). - Use the
Leftfunction to extract all characters to the left of that position, minus one character to exclude the dot itself.
Example code for a reusable function:
Function GetWorkbookNameWithoutExt() As String
Dim fullPath As String
fullPath = ThisWorkbook.Name
If InStr(fullPath, '.') > 0 Then
GetWorkbookNameWithoutExt = Left(fullPath, InStrRev(fullPath, '.') - 1)
Else
GetWorkbookNameWithoutExt = fullPath
End If
End Function
The If statement in the example above is a safety mechanism. It checks if a period exists at all. Without this check, InStrRev would return 0, and Left(string, -1) would cause the macro to crash with an "Invalid procedure call or argument" error.
Using FileSystemObject for Advanced Parsing
For developers who are performing complex file operations, the Scripting.FileSystemObject (FSO) provides a more elegant solution. FSO is a part of the Microsoft Scripting Runtime library and includes a GetBaseName method specifically designed to return a filename without its extension.
To use FSO, you can either enable the reference to "Microsoft Scripting Runtime" in the VBA editor (Tools > References) or use late binding. Late binding is often preferred for distribution because it prevents "Missing Reference" errors on different versions of Windows or Office.
The process using FSO works as follows:
- Create an instance of the
Scripting.FileSystemObject. - Pass the full path of the workbook (using
ThisWorkbook.FullName) into theGetBaseNamemethod. - The method automatically handles the logic of finding the final period and returning the prefix.
This method is significantly more robust than manual string manipulation because it is a native Windows API wrapper that handles edge cases, such as files with no extensions or files located in directories with complex naming conventions, more reliably than a custom string function.
Common Problems and Edge Cases
When automating workbook naming, several common pitfalls can disrupt the workflow. The most frequent issue is the "Unsaved Workbook" error. As mentioned, a new workbook named "Book1" has no extension. If your code assumes a dot is always present, it will fail. Always validate the existence of the delimiter before attempting to subtract from its position.
Another complication arises with hidden extensions. In Windows File Explorer, users can choose to "Hide extensions for known file types." While this changes how the user sees the file, it does not change how VBA sees the Name property. VBA always sees the extension if the file is saved. A common misconception is that if extensions are hidden in Windows, ThisWorkbook.Name will not return them. This is false; the internal property remains consistent regardless of OS display settings.
Additionally, consider the impact of different file formats. Whether the file is .xls, .xlsx, .xlsm, or .xlsb, the logic of searching for the last period remains the same. However, if you are working with legacy files or specialized add-ins (.xlam), ensure that your logic doesn't accidentally strip necessary identifying markers if you are renaming the file programmatically.
Comparing String Manipulation vs. FSO
Choosing between the Left/InStrRev method and the FileSystemObject method depends on the scope of your project. Here is a detailed comparison:
- Performance: String manipulation using native VBA functions is marginally faster because it does not require initializing an external COM object. For a single filename, the difference is nanoseconds; for thousands of files in a loop, it may be noticeable.
- Simplicity: The
Left/InStrRevapproach is self-contained. It requires no external libraries and works instantly in any Excel environment. - Reliability: FSO is more reliable for complex paths. If you are dealing with full directory paths (e.g., C:\Users\Name\Documents\File.xlsx) rather than just the filename,
GetBaseNameis far superior because it ignores the folder path and only looks at the final segment of the string. - Portability: Native VBA functions are more portable. FSO is specific to Windows. While rare, if a macro is intended to run on Excel for Mac, FSO will not work, and string manipulation is the only viable path.
Frequently Asked Questions
What happens if my filename has multiple dots?
If you use InStr, the code will cut the name at the first dot it finds. However, by using InStrRev, VBA starts searching from the right side of the string. This ensures that only the final extension is removed, leaving any version numbers or date markers (like "Report.v2.2023.xlsx") intact as "Report.v2.2023".
Can I get the name without the extension for a different workbook?
Yes. Instead of using ThisWorkbook.Name, you can use a workbook variable. For example, if you have set Set wb = Workbooks.Open("C:\test.xlsx"), you would apply the same logic to wb.Name. The logic remains identical regardless of which workbook object is being referenced.
Why does my code throw an "Invalid procedure call" error?
This error almost always occurs because the workbook has not been saved. When a workbook is unsaved, InStrRev returns 0. When your code then tries to execute Left(name, 0 - 1), it asks VBA to take -1 characters from the left, which is mathematically impossible and triggers the crash. Adding an If InStr(name, ".") > 0 check prevents this.
Is there a way to do this without VBA using a formula?
Yes, although it is more complex. You can use a combination of LEFT, FIND, and SUBSTITUTE. A common trick is to substitute the last period with a unique character, find that character, and then slice the string. However, for dynamic workbook naming, VBA is the standard approach as formulas cannot easily reference the current filename without a defined name or a small VBA helper function.
Does this method work for .xlsb or .xlsm files?
Yes. Because these methods look for the period (.) and not the specific letters after it, the length of the extension (3 characters for .xls or 4 characters for .xlsx/.xlsm) does not matter. The code simply removes everything from the last period to the end of the string.