Last updated on September 20, 2024 By Victor Chan
Ever find yourself spending way too much time manually saving each worksheet in an Excel workbook as a separate file? If so, you're not alone. This repetitive task can be a real time-drainer, especially if you're dealing with a workbook that has numerous sheets. The good news is that there's a powerful solution: Visual Basic for Applications (VBA).
In this tutorial, we'll walk you through how to use VBA to automate the process of exporting all worksheets in a workbook to individual Excel files. By the end of this guide, you'll be able to save hours of work and streamline your Excel tasks like a pro.
Download FREE Excel Workbook
Step 1: Sign up for free Click Here
Step 2: Log in for access Click Here
Step 3: Download file Export-Excel-Worksheets-with-VBA.zip
Are you new to Excel VBA Macros?
• Find out how to enable and disable macros in Excel with this tutorial
• Save time and effort by copying VBA macros from one workbook to another with these instructions
What is VBA?
Visual Basic for Applications (VBA) is a programming language built into Microsoft Office applications like Excel. It allows you to automate tasks by writing scripts called macros. With VBA, you can perform complex operations with just a click of a button, saving you a significant amount of time.
Why Use VBA to Export Worksheets?
Before we dive into the VBA code, let's set up your Excel environment to enable VBA scripting.
Enabling the Developer Tab
The Developer tab provides access to VBA and other advanced features.
You'll now see the Developer tab appear in the Excel ribbon.
Accessing the Visual Basic Editor
The Visual Basic Editor (VBE) window will open, where you'll write your VBA code.
Let's start by creating a macro that exports a single worksheet to a separate Excel file.
Step 1: Preparing Your Workbook
Step 2: Writing the VBA Code
[VBA Code Box]
Option Explicit
Sub Export_One_Worksheet_To_XLSX()
Dim wb As Workbook
Dim ws As Worksheet
Dim SaveToDirectory As String
Dim fName As String
On Error GoTo ErrorHandler ' Start error handling
Set wb = ActiveWorkbook
' Get the path of the Active workbook
SaveToDirectory = wb.Path &"\"
If SaveToDirectory = "\" Then
MsgBox "Please save the workbook before running this macro.", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Export first worksheet
Set ws = wb.Worksheets(1)
ws.Copy
fName = SaveToDirectory &ws.Name &".xlsx"
With ActiveWorkbook
.SaveAs Filename:=fName, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
.Close SaveChanges:=False
End With
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "First worksheet has been exported successfully.", vbInformation
Exit Sub
ErrorHandler:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "An error occurred: " &Err.Description, vbCritical ' Notify the user of the error
End Sub
Step 3: Running the Macro
Step 4: Verifying the Result
Check the folder where your workbook is saved. You should see a new Excel file named after your first worksheet, containing only that sheet.
Now, let's modify the code to export all worksheets in the workbook.
Step 1: Modifying the VBA Code
Update your VBA code as follows:
[VBA Code Box]
Option Explicit
Sub Export_All_Worksheets_To_XLSX_v1()
Dim wb As Workbook
Dim ws As Worksheet
Dim SaveToDirectory As String
Dim fName As String
On Error GoTo ErrorHandler ' Start error handling
Set wb = ActiveWorkbook
' Get the path of the Active workbook
SaveToDirectory = wb.Path &"\"
If SaveToDirectory = "\" Then
MsgBox "Please save the workbook before running this macro.", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Loop through each worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Copy
fName = SaveToDirectory &ws.Name &".xlsx"
With ActiveWorkbook
.SaveAs Filename:=fName, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
.Close SaveChanges:=False
End With
Next ws
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "All worksheets have been exported successfully.", vbInformation
Exit Sub
ErrorHandler:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "An error occurred: " &Err.Description, vbCritical ' Notify the user of the error
End Sub
Step 2: Understanding the Code
Step 3: Running the Macro
Step 4: Verifying the Results
Check the folder where your workbook is saved. You should see individual Excel files for each worksheet in your workbook.
To make the code more robust, we'll add a function to clean up worksheet names and improve error handling.
Step 1: Handling Invalid Characters
File names cannot contain certain characters (\ / : * ? " < > |). We'll create a function to replace these characters with underscores.
Add the following function to your module:
[VBA Code Box]
' Custom function to clean invalid characters from worksheet name for file saving
Function CleanFileName(strName As String) As String
' Replace invalid characters with underscore
Const invalidChars As String = "\/:*?""<>|"
Dim i As Integer
For i = 1 To Len(invalidChars)
strName = Replace(strName, Mid(invalidChars, i, 1), "_")
Next i
' Trim any trailing spaces or dots from the file name
Do While Right(strName, 1) = " " Or Right(strName, 1) = "."
strName = Left(strName, Len(strName) - 1)
Loop
' Return the cleaned name
CleanFileName = strName
End Function
Step 2: Updating the Main Subroutine
Modify the line where fName is defined:
[VBA Code Box]
' Clean the worksheet name before saving to new file
fName = SaveToDirectory &CleanFileName(ws.Name) &".xlsx"
Step 3: Full Enhanced Code
Here's the complete enhanced VBA code:
[VBA Code Box]
Option Explicit
' *** Module Overview ***
' This module automates the process of exporting all worksheets in the active workbook
' as .xlsx files, handling both system restrictions and errors efficiently.
'
' Key Features:
' - Invalid characters in worksheet names are automatically cleaned.
' - Error handling is included to restore Excel settings and notify the user in case of an error.
'
' ### Subroutines and Functions ###
'
' - Sub Export_Worksheets_To_XLSX:
' - Checks if the workbook has been saved before proceeding with the export.
' - Disables screen updates and alerts to enhance performance and prevent unnecessary prompts.
' - Exports the all worksheets in the active workbook to new .xlsx files.
' - Cleans the worksheet names for file saving by replacing invalid characters and ensuring
' compliance with Windows file naming rules.
' - Error handling ensures that screen updates and alerts are always restored, even if an error occurs.
' - Displays a message box to confirm the successful export.
'
' - Function CleanFileName:
' - Replaces any invalid characters (e.g., \/:*?"<>|) with underscores.
'
' *** End of Module Overview ***
Sub Export_All_Worksheets_To_XLSX_v2()
Dim wb As Workbook
Dim ws As Worksheet
Dim SaveToDirectory As String
Dim fName As String
On Error GoTo ErrorHandler ' Start error handling
Set wb = ActiveWorkbook
' Get the path of the Active Workbook
SaveToDirectory = wb.Path &"\"
If SaveToDirectory = "\" Then
MsgBox "Please save the workbook before running this macro.", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Loop through each worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Copy
' Clean the worksheet name before saving to new file
fName = SaveToDirectory &CleanFileName(ws.Name) &".xlsx"
With ActiveWorkbook
.SaveAs Filename:=fName, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
.Close SaveChanges:=False
End With
Next ws
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "First worksheet has been exported successfully.", vbInformation
Exit Sub ' Exit to avoid error handler running if not needed
ErrorHandler:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "An error occurred: " &Err.Description, vbCritical ' Notify the user of the error
End Sub
' Custom function to clean invalid characters from worksheet name for file saving
Function CleanFileName(strName As String) As String
' Replace invalid characters with underscore
Const invalidChars As String = "\/:*?""<>|"
Dim i As Integer
For i = 1 To Len(invalidChars)
strName = Replace(strName, Mid(invalidChars, i, 1), "_")
Next i
' Trim any trailing spaces or dots from the file name
Do While Right(strName, 1) = " " Or Right(strName, 1) = "."
strName = Left(strName, Len(strName) - 1)
Loop
' Return the cleaned name
CleanFileName = strName
End Function
To use this macro anytime, even in different workbooks, we'll store it in the Personal Macro Workbook and add a custom button to the Excel ribbon.
Step 1: Creating the Personal Macro Workbook
This action creates a hidden workbook named PERSONAL.XLSB that opens automatically with Excel.
Step 2: Adding the VBA Code to the Personal Macro Workbook
Step 3: Saving and Closing the VBE
Step 4: Adding a Custom Button to the Ribbon
Step 5: Using Your Custom Button
Your custom button now appears in the ribbon under your new tab. Click it anytime to run your macro and export all worksheets in the active workbook.
Now that you've mastered automating worksheet exports using VBA, why not take your skills to the next level? If you’re ready to unlock the full potential of Excel, check out my online VBA course.
Over 500 students have already transformed their Excel abilities with this course, and it's received outstanding reviews on Trustpilot. Whether you’re new to VBA or looking to sharpen your skills, this course is designed to help you automate your Excel tasks with confidence and ease.
Don't miss out on this opportunity to supercharge your Excel productivity. Click here to enroll and start your journey today!
Hi, I'm Victor!
Are you struggling with complex Excel tasks? Feeling overwhelmed by spreadsheets that are hard to use?
Many people believe mastering Excel is about learning shortcuts, functions, and formulas. But this overlooks the importance of building practical, real-world applications. It's not just about knowing the tools. It's about using them effectively.
That's where I come in. You'll get a unique perspective to Excel training from me. I have over 20 years of experience at Deloitte and two global tech companies. And I know what can make a difference in your career.
Let me help you integrate Excel into your professional life. Starting today. Read one of my articles, watch one of my videos. Then apply the new technique to your work. You'll see the difference immediately!
Discover the PROVEN Blueprint for transforming your Excel skills, supercharging your productivity, and standing out in your career! My course helps you to learn Excel VBA and save hours of time even if you have zero prior experience with programming.
Solve tricky Excel problems and take your work to the next level! Get customized solutions for your unique needs. Save time and gain insights with truly expert Excel solutions from only $97 per task.
Get a clear overview of your project progress using the Excel project timeline. Use it to communicate the big picture, track task progress, and stay on top of your project goals. Stay organized with our project timeline!
Our cheat sheets provide quick and easy reference to commonly used Excel VBA concepts and code snippets.
Unlock new levels of productivity and efficiency with our cheat sheets, and write VBA code like a pro in no time.
RECOMMENDED READING
Are you looking to upskill and stay ahead of the curve? Excel is a powerful tool that keeps growing in demand. We round up the best online courses for learning Excel.
Are you looking to up your spreadsheet game? Excel is an invaluable tool that can help you stay organized and save time. From data analysis to budgets, Excel can do it all!
Today, having Excel skills is more critical than ever. Those who know how to use Excel are more likely to find higher-paying jobs. And get promoted faster.