How to Export Excel Worksheets to Separate Files Using VBA

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

Introduction to VBA

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?

  • Automate repetitive tasks: Save time by letting the computer do the heavy lifting.
  • Reduce errors: Automation minimizes the risk of mistakes that can occur with manual operations.
  • Enhance efficiency: Perform tasks much faster than doing them manually.

Setting Up Your Excel Environment

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.

  • 1. Open Excel.
  • 2. Right-click on any ribbon tab and select Customize the Ribbon.
  • 3. In the Excel Options dialog, check the box next to Developer in the right pane.
  • 4. Click OK.

You'll now see the Developer tab appear in the Excel ribbon.


Accessing the Visual Basic Editor

  • 1. Click on the Developer tab.
  • 2. Click on Visual Basic or press ALT + F11.

The Visual Basic Editor (VBE) window will open, where you'll write your VBA code.

Exporting a Single Worksheet

Let's start by creating a macro that exports a single worksheet to a separate Excel file.

Step 1: Preparing Your Workbook

  • 1. Save your current workbook as a Macro-Enabled Workbook with the .xlsm extension.
  • - Go to File > Save As.
  • - Choose Excel Macro-Enabled Workbook (*.xlsm) from the file type dropdown.
  • - Name it Worksheet_Exporter.xlsm.

Step 2: Writing the VBA Code

  • 1. In the VBE, insert a new module:
  • - Right-click on ThisWorkbook or any existing module.
  • - Select Insert > Module.
  • 2. Rename the module to ExportOneSheet:
  • - In the Properties window (press F4 if not visible), change the Name property to ExportOneSheet.
  • 3. In the new module, type the following 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

  • 1. Return to Excel.
  • 2. Make sure your workbook has at least one worksheet with data.
  • 3. Go back to the VBE.
  • 4. Place the cursor inside the Export_One_Worksheet_To_XLSX subroutine.
  • 5. Press F5 or click Run Sub/UserForm (green play button).
  • 6. A message box should appear saying "First worksheet has been exported successfully."

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.

Automating the Export of All Worksheets

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

  • - Looping Through Worksheets: The For Each ws In wb.Worksheets loop goes through every worksheet in the workbook.
  • - Copying and Saving Each Worksheet: Within the loop, each worksheet is copied and saved as a separate .xlsx file.
  • - Error Handling: The On Error GoTo ErrorHandler statement ensures that any errors are caught, and resources are cleaned up properly.

Step 3: Running the Macro

  • 1. Save your VBA code.
  • 2. Return to Excel.
  • 3. Ensure your workbook has multiple worksheets with data.
  • 4. Run the Export_All_Worksheets_To_XLSX macro as before.
  • 5. A message box should appear saying "All worksheets have been exported successfully."

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.

Enhancing the VBA Code

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 





Making the Macro Easily Accessible

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

  • 1. In Excel, start recording a new macro:
    • - Go to the Developer tab.
    • - Click on Record Macro.
    • 2. In the Record Macro dialog:
    • - Name the macro anything you like (e.g., TempMacro).
    • - Set Store macro in to Personal Macro Workbook.
    • - Click OK.
    • 3. Immediately stop recording:
    • - Click Stop Recording on the Developer tab.

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

  • 1. Open the VBE (ALT + F11).
  • 2. In the Project Explorer window, find VBAProject (PERSONAL.XLSB).
  • 3. Insert a new module:
    • - Right-click on Modules under PERSONAL.XLSB.
    • - Select Insert > Module.
    • 4. Paste your enhanced VBA code into this module.

Step 3: Saving and Closing the VBE

  • 1. Save your changes in the VBE.
  • 2. Close the VBE window.

Step 4: Adding a Custom Button to the Ribbon

  • 1. Right-click on the Excel ribbon and select Customize the Ribbon.
  • 2. In the Excel Options dialog:
    • - On the right, click New Tab.
    • - Select the new tab (e.g., New Tab (Custom)) and click Rename to name it (e.g., Custom Menu).
    • - Under the new tab, select New Group (Custom) and click Rename to name it (e.g., Export Sheets).
    • 3. On the left, under Choose commands from, select Macros.
    • 4. Find your macro (it should be something like
    • 5. Select the macro and click Add >> to add it to your new group.
    • 6. With the macro selected in your new group, click Rename to change its display name and icon.
    • 7. Click OK to save your changes.

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.

What Next

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!


Connect on YouTube, LinkedIn, Twitter.

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.

JOIN FREE EMAIL NEWSLETTER

Step up your Excel game! Join our free email newsletter and get updates on how to become more awesome at Excel.