Category: VBA

Automation scripts, macros, and custom functions to speed up daily office workflows.

  • How to Automatically Send Emails with Attachments from Excel Using VBA

    Sending repetitive monthly invoices, individual performance reports, or automated updates to multiple clients manually takes hours. Using Excel VBA to integrate directly with Microsoft Outlook allows you to send customized emails with dedicated file attachments in just seconds.

    In this step-by-step guide, you will learn how to set up a clean, reliable VBA macro that reads recipient email addresses, custom subjects, body text, and specific attachment file paths directly from your Excel sheet.


    Why Automate Outlook Emails via Excel VBA?

    Automating your email dispatch directly from your workbook offers immediate workflow advantages:

    • Batch Dispatching: Send personalized emails to dozens of recipients with a single click.
    • Dynamic Attachments: Attach individualized PDF reports or statements dynamically per row.
    • Draft Review Mode: Choose between displaying emails for manual review or sending them out instantly.

    Step 1: Set Up Your Worksheet Layout

    Before adding the macro, ensure your active worksheet has headers in Row 1 matching the structure below:

    • Column A: Recipient Email Address (e.g., client@example.com)
    • Column B: Email Subject Line
    • Column C: Personal Salutation / Name
    • Column D: Full Path to File Attachment (e.g., C:\Reports\Invoice_101.pdf)

    Step 2: Copy and Paste the Email VBA Code

    Press Alt + F11 to open the Visual Basic Editor, click Insert ➔ Module, and paste the code below:

    Sub SendAutomatedEmailsWithAttachments()
        Dim OutlookApp As Object
        Dim OutlookMail As Object
        Dim ws As Worksheet
        Dim lastRow As Long
        Dim i As Long
        Dim emailTo As String
        Dim emailSubject As String
        Dim clientName As String
        Dim attachmentPath As String
        Dim mailBody As String
        
        Set ws = ActiveSheet
        lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        
        If lastRow < 2 Then
            MsgBox "No email data found starting in Row 2!", vbExclamation, "Excel Owl Automation"
            Exit Sub
        End If
        
        ' Initialize Outlook Application instance
        On Error Resume Next
        Set OutlookApp = GetObject(, "Outlook.Application")
        If OutlookApp Is Nothing Then
            Set OutlookApp = CreateObject("Outlook.Application")
        End If
        On Error GoTo 0
        
        Application.ScreenUpdating = False
        
        ' Loop through each row in worksheet
        For i = 2 To lastRow
            emailTo = ws.Cells(i, 1).Value
            emailSubject = ws.Cells(i, 2).Value
            clientName = ws.Cells(i, 3).Value
            attachmentPath = ws.Cells(i, 4).Value
            
            If emailTo <> "" Then
                Set OutlookMail = OutlookApp.CreateItem(0)
                
                ' Construct HTML Email Body
                mailBody = "<p>Dear " & clientName & ",</p>" & _
                           "<p>Please find attached your requested report.</p>" & _
                           "<p>Best regards,<br><strong>Excel Owl Automation Team</strong></p>"
                
                With OutlookMail
                    .To = emailTo
                    .Subject = emailSubject
                    .HTMLBody = mailBody
                    
                    ' Attach file if valid file path exists
                    If attachmentPath <> "" And Dir(attachmentPath) <> "" Then
                        .Attachments.Add attachmentPath
                    End If
                    
                    ' Change to .Send to dispatch emails instantly without preview
                    .Display 
                End With
            End If
        Next i
        
        Application.ScreenUpdating = True
        
        MsgBox "All emails processed successfully!", vbInformation, "Excel Owl Automation"
    End Sub

    Step 3: Run and Preview Your Emails

    Return to Excel, press Alt + F8, select SendAutomatedEmailsWithAttachments, and click Run. The macro will create customized Outlook email windows with attached files ready for inspection!

    💡 Pro Tip: Switch from Preview to Direct Send
    By default, this script uses .Display so you can review emails before sending. Once you verify your workflow, change line 52 from .Display to .Send to dispatch all emails in the background automatically.


    Step 4: Save File as .xlsm

    Remember to save your Excel file as an Excel Macro-Enabled Workbook (*.xlsm) to preserve your VBA automation.

  • How to Merge Multiple Excel Sheets into a Single PDF File Using VBA

    When preparing end-of-month financial packets, client presentations, or audit files, sending dozens of separate PDF files can look disorganized. Combining multiple worksheets into a single, seamless PDF document is much more professional.

    In this guide, you will learn how to use a simple Excel VBA macro that automatically selects multiple worksheets (or all visible sheets) and exports them into a single, multi-page PDF document with just one click.


    Why Combine Sheets into One PDF via VBA?

    Merging multiple tabs into one PDF manually requires repeatedly rearranging print settings or using external PDF merging tools. Automating this workflow provides:

    • Single-File Output: Combines all specified report tabs into one clean PDF document.
    • Automatic Page Ordering: Keeps your sheets in the exact order they appear in your Excel workbook.
    • Third-Party Tool Elimination: No need to upload confidential spreadsheets to free online PDF mergers.

    Step 1: Open the VBA Editor Window

    1. Open your Excel workbook containing the sheets you wish to combine into a PDF.
    2. Press Alt + F11 (Option + F11 on Mac) to open the Visual Basic Editor.
    3. In the top menu, click Insert ➔ Module to open a clean code window.

    Step 2: Copy and Paste the Combined PDF VBA Code

    Copy the code block below and paste it directly into your blank module window:

    Sub ExportAllSheetsToSinglePDF()
        Dim folderPath As String
        Dim pdfFileName As String
        Dim fullPdfPath As String
        Dim ws As Worksheet
        Dim sheetArray() As String
        Dim count As Long
        
        ' 1. Get current workbook folder path
        folderPath = Application.ActiveWorkbook.Path
        
        If folderPath = "" Then
            MsgBox "Please save your Excel workbook first before running this macro!", vbExclamation, "File Not Saved"
            Exit Sub
        End If
        
        ' 2. Define output PDF file name
        pdfFileName = "Combined_Report_" & Format(Date, "YYYYMMDD") & ".pdf"
        fullPdfPath = folderPath & "\" & pdfFileName
        
        ' 3. Collect all visible worksheets into an array
        count = 0
        For Each ws In ActiveWorkbook.Worksheets
            If ws.Visible = xlSheetVisible Then
                ReDim Preserve sheetArray(count)
                sheetArray(count) = ws.Name
                count = count + 1
            End If
        Next ws
        
        If count = 0 Then
            MsgBox "No visible sheets found to export!", vbExclamation, "Excel Owl Automation"
            Exit Sub
        End If
        
        ' 4. Select visible sheets and export as a single PDF
        Application.ScreenUpdating = False
        
        Worksheets(sheetArray).Select
        ActiveSheet.ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:=fullPdfPath, _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=True
            
        ' Reselect the first sheet to un-group worksheets
        Worksheets(sheetArray(0)).Select
        
        Application.ScreenUpdating = True
        
        MsgBox "All visible sheets exported successfully to:" & vbCrLf & pdfFileName, vbInformation, "Excel Owl Automation"
    End Sub

    Step 3: Run the Macro Using Alt + F8

    Execute your single PDF generator directly from Excel:

    1. Switch back to your main Excel workbook window.
    2. Press Alt + F8 (or Option + F8 on Mac) to bring up the Macro dialog box.
    3. Select ExportAllSheetsToSinglePDF from the list.
    4. Click Run. The combined PDF will open automatically upon completion!

    💡 Pro Tip: Exclude Specific Tabs
    If you want to skip certain administrative or lookup tabs, simply right-click those sheet tabs in Excel and select Hide. The macro automatically ignores hidden sheets!


    Step 4: Save as Macro-Enabled Workbook (.xlsm)

    To retain your macro code for future reporting runs, make sure to save in the correct format:

    1. Click File ➔ Save As (or press F12).
    2. In the Save as type drop-down, select Excel Macro-Enabled Workbook (*.xlsm).
    3. Click Save.

    ⚠️ Important Note: Standard .xlsx files cannot store macros. Saving as .xlsx will permanently erase your VBA script.

  • How to Split Data into Multiple Sheets Based on Column Value in Excel (VBA)

    Working with large master datasets—like sales records, inventory lists, or employee rosters—often requires separating the data into individual tabs based on specific categories like Region, Department, or Sales Rep.

    In this guide, you will learn how to use a clean Excel VBA macro that automatically filters your master sheet and splits the rows into dedicated worksheets based on unique values in a chosen column with just one click.


    Why Automate Data Splitting with VBA?

    Manually filtering and copying data into new sheets is repetitive and error-prone. Automating this task provides key advantages:

    • Dynamic Tab Creation: Automatically creates new worksheets for unique values (e.g., North, South, East, West) if they don’t already exist.
    • Preserves Formatting & Headers: Ensures every newly generated tab carries over the exact column headers from the master table.
    • Instant Execution: Processes thousands of rows across dozens of unique categories in seconds.

    Step 1: Open the VBA Editor Window

    1. Open your Excel workbook containing the master dataset.
    2. Press Alt + F11 (Option + F11 on Mac) to open the Visual Basic Editor.
    3. In the top menu, click Insert ➔ Module to open a clean code module.

    Step 2: Copy and Paste the Data Split VBA Code

    Copy the code block below and paste it directly into your module window:

    Sub SplitDataIntoSheets()
        Dim masterWs As Worksheet
        Dim newWs As Worksheet
        Dim lastRow As Long
        Dim splitCol As Long
        Dim uniqueVals As Collection
        Dim cellVal As Variant
        Dim i As Long
        Dim val As Variant
        
        ' Set master worksheet
        Set masterWs = ActiveSheet
        
        ' Column index to split by (Column A = 1, Column B = 2, Column C = 3, etc.)
        splitCol = 1 
        
        ' Find last row of data
        lastRow = masterWs.Cells(masterWs.Rows.Count, splitCol).End(xlUp).Row
        If lastRow < 2 Then
            MsgBox "No data found to split!", vbExclamation, "Excel Owl Automation"
            Exit Sub
        End If
        
        ' Optimize performance
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
        
        ' Extract unique categories
        Set uniqueVals = New Collection
        On Error Resume Next
        For i = 2 To lastRow
            cellVal = masterWs.Cells(i, splitCol).Value
            If cellVal <> "" Then
                uniqueVals.Add cellVal, CStr(cellVal)
            End If
        Next i
        On Error GoTo 0
        
        ' Loop through unique categories and create sheets
        For Each val In uniqueVals
            ' Check if sheet already exists, delete if necessary
            On Error Resume Next
            Worksheets(CStr(val)).Delete
            On Error GoTo 0
            
            ' Add new sheet
            Set newWs = Worksheets.Add(After:=Worksheets(Worksheets.Count))
            newWs.Name = CStr(val)
            
            ' Filter and copy data from Master
            masterWs.Range("A1").AutoFilter Field:=splitCol, Criteria1:=val
            masterWs.UsedRange.SpecialCells(xlCellTypeVisible).Copy newWs.Range("A1")
            
            ' Auto-fit columns
            newWs.Columns.AutoFit
        Next val
        
        ' Clear filter and restore settings
        masterWs.AutoFilterMode = False
        masterWs.Activate
        Application.ScreenUpdating = True
        Application.DisplayAlerts = True
        
        MsgBox uniqueVals.Count & " sheets created successfully!", vbInformation, "Excel Owl Automation"
    End Sub

    Step 3: Run the Macro Using Alt + F8

    Run your data-splitting script whenever you update your master list:

    1. Switch back to your main Excel window on the master sheet.
    2. Press Alt + F8 (or Option + F8 on Mac) to open the Macro dialog.
    3. Select SplitDataIntoSheets from the list and click Run.

    💡 Pro Tip: Target a Different Column
    By default, this script splits data using Column A (splitCol = 1). To split by Column B or C instead, simply change splitCol = 2 or splitCol = 3 in line 13 of the code.


    Step 4: Save as Macro-Enabled Workbook (.xlsm)

    Make sure to save your file in the macro-enabled format to keep your script intact:

    1. Click File ➔ Save As (or press F12).
    2. In the Save as type menu, choose Excel Macro-Enabled Workbook (*.xlsm).
    3. Click Save.

    ⚠️ Important Note: Standard .xlsx files do not support macro code. Saving as .xlsx will erase your script permanently!

  • How to Merge Multiple Excel Files into One Sheet Using VBA (Automated)

    If you routinely receive separate weekly or monthly report files from multiple team members, opening each workbook to manually copy and paste rows into a master file is both time-consuming and error-prone.

    In this guide, you will learn how to use a powerful Excel VBA macro that automatically prompts you to select a folder and merges data from all Excel files inside it into a single **Master Sheet** with just one click.


    Why Automate File Consolidation?

    Consolidating external files manually is one of the most common productivity bottlenecks in business operations. Automating it gives you:

    • Dynamic Folder Selection: Pick any folder on your computer using a clean pop-up window.
    • Automatic Header Protection: Retains headers from the first file while skipping duplicate headers from subsequent workbooks.
    • Fast Batch Processing: Handles dozens of `.xlsx` files in seconds without manually opening each one.

    Step 1: Open the VBA Editor Window

    1. Open a blank Excel workbook.
    2. Press Alt + F11 (Option + F11 on Mac) to open the Visual Basic Editor.
    3. In the top menu bar, click Insert ➔ Module to open a clean code window.

    Step 2: Copy and Paste the File Merge VBA Code

    Copy the code block below and paste it directly into your blank module window:

    Sub CombineMultipleFiles()
        Dim folderPath As String
        Dim fileName As String
        Dim masterWs As Worksheet
        Dim sourceWorkbook As Workbook
        Dim sourceWs As Worksheet
        Dim lastRow As Long
        Dim masterLastRow As Long
        Dim isFirstFile As Boolean
        Dim fileDialog As FileDialog
        
        ' 1. Allow user to select a folder
        Set fileDialog = Application.FileDialog(msoFileDialogFolderPicker)
        fileDialog.Title = "Select the Folder Containing Excel Files to Merge"
        
        If fileDialog.Show = -1 Then
            folderPath = fileDialog.SelectedItems(1) & "\"
        Else
            MsgBox "No folder selected. Macro canceled.", vbExclamation, "Excel Owl Automation"
            Exit Sub
        End If
        
        ' 2. Optimize execution speed
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
        
        ' 3. Set up Master Sheet
        Set masterWs = ActiveWorkbook.Sheets(1)
        masterWs.Name = "Master Data"
        masterWs.Cells.Clear
        
        isFirstFile = True
        fileName = Dir(folderPath & "*.xlsx*")
        
        ' 4. Loop through each Excel file in folder
        Do While fileName <> ""
            ' Skip the active workbook if saved in same folder
            If fileName <> ActiveWorkbook.Name Then
                Set sourceWorkbook = Workbooks.Open(folderPath & fileName, ReadOnly:=True)
                Set sourceWs = sourceWorkbook.Sheets(1)
                
                lastRow = sourceWs.Cells(sourceWs.Rows.Count, "A").End(xlUp).Row
                
                If lastRow >= 1 Then
                    If isFirstFile Then
                        ' Copy header + data from first file
                        sourceWs.Rows("1:" & lastRow).Copy masterWs.Range("A1")
                        isFirstFile = False
                    Else
                        ' Find next blank row in Master and copy data only (skip header)
                        masterLastRow = masterWs.Cells(masterWs.Rows.Count, "A").End(xlUp).Row + 1
                        sourceWs.Rows("2:" & lastRow).Copy masterWs.Range("A" & masterLastRow)
                    End If
                End If
                
                sourceWorkbook.Close SaveChanges:=False
            End If
            fileName = Dir
        Loop
        
        ' 5. Auto-fit columns & restore settings
        masterWs.Columns.AutoFit
        Application.ScreenUpdating = True
        Application.DisplayAlerts = True
        
        MsgBox "All Excel files successfully merged into Master Data!", vbInformation, "Excel Owl Automation"
    End Sub

    Step 3: Run the Macro Using Alt + F8

    You can trigger this automatic file-merging process straight from your workbook:

    1. Switch back to your main Excel window.
    2. Press Alt + F8 (or Option + F8 on Mac) to open the Macro dialog.
    3. Select CombineMultipleFiles from the list and click Run.
    4. A window will pop up—select the folder containing your target Excel files and click OK.

    💡 Pro Tip: Folder Selection Shortcut
    Make sure all your source files are saved inside a single folder before running the script so VBA can loop through every file smoothly!


    Step 4: Save as Macro-Enabled Workbook (.xlsm)

    To retain your macro code for future file consolidations, save your file in the macro-enabled format:

    1. Click File ➔ Save As (or press F12).
    2. In the Save as type drop-down, choose Excel Macro-Enabled Workbook (*.xlsm).
    3. Click Save.

    ⚠️ Important Note: Standard .xlsx files cannot store macro scripts. Saving as a normal .xlsx workbook will permanently delete your code!

  • How to Export Excel Sheets as Separate PDFs Using VBA (One Click)

    If you need to send individual monthly reports, invoices, or department summaries to clients or executives, manually saving each sheet as a separate PDF file takes unnecessary time and effort.

    In this guide, you will learn how to run a simple Excel VBA macro that automatically exports every worksheet in your workbook (or selected sheets) into clean, individual PDF files with just one click.


    Why Automate PDF Exports with VBA?

    Automating your PDF generation workflow eliminates daily administrative bottlenecks:

    • Instant Batch Saving: Export dozens of sheets in seconds instead of repeating File ➔ Export ➔ PDF manually.
    • Standardized Naming: Automatically names each PDF file using the exact worksheet title.
    • Same-Folder Organization: Automatically saves output PDF files directly into the same folder as your Excel workbook.

    Step 1: Open the VBA Editor Window

    1. Open your Excel workbook containing the sheets you want to export.
    2. Press Alt + F11 (Option + F11 on Mac) to launch the Visual Basic Editor.
    3. In the top menu, click Insert ➔ Module to create a new blank code window.

    Step 2: Copy and Paste the PDF Export VBA Code

    Copy the code block below and paste it directly into your blank module window:

    Sub ExportSheetsToPDF()
        Dim ws As Worksheet
        Dim folderPath As String
        Dim pdfFilePath As String
        Dim exportedCount As Long
        
        ' 1. Get the current folder path of the workbook
        folderPath = Application.ActiveWorkbook.Path
        
        ' Ensure file is saved before running
        If folderPath = "" Then
            MsgBox "Please save your Excel workbook first before running this macro!", vbExclamation, "File Not Saved"
            Exit Sub
        End If
        
        ' Add trailing slash to path
        folderPath = folderPath & "\"
        
        ' 2. Pause screen updating for speed
        Application.ScreenUpdating = False
        exportedCount = 0
        
        ' 3. Loop through each visible worksheet
        For Each ws In ActiveWorkbook.Worksheets
            If ws.Visible = xlSheetVisible Then
                ' Define output path (FolderPath + SheetName + .pdf)
                pdfFilePath = folderPath & ws.Name & ".pdf"
                
                ' Export sheet as PDF
                ws.ExportAsFixedFormat _
                    Type:=xlTypePDF, _
                    Filename:=pdfFilePath, _
                    Quality:=xlQualityStandard, _
                    IncludeDocProperties:=True, _
                    IgnorePrintAreas:=False, _
                    OpenAfterPublish:=False
                    
                exportedCount = exportedCount + 1
            End If
        Next ws
        
        ' 4. Re-enable screen updating
        Application.ScreenUpdating = True
        
        ' 5. Completion notice
        MsgBox exportedCount & " sheets successfully exported as PDFs into your folder!", vbInformation, "Excel Owl Automation"
    End Sub

    Step 3: Run the Macro Using Alt + F8

    Run your new PDF generator directly from your Excel sheet whenever needed:

    1. Switch back to your main Excel window.
    2. Press Alt + F8 (or Option + F8 on Mac) to open the Macro dialog box.
    3. Select ExportSheetsToPDF from the list.
    4. Click Run.

    💡 Pro Tip: Hidden Sheets Protection
    This macro automatically skips hidden worksheets, ensuring only active and visible sheets are exported to PDF!


    Step 4: Save as Macro-Enabled Workbook (.xlsm)

    To preserve your macro script for ongoing use, make sure to save your file correctly:

    1. Click File ➔ Save As (or press F12).
    2. In the Save as type drop-down menu, select Excel Macro-Enabled Workbook (*.xlsm).
    3. Click Save.

    ⚠️ Important Note: Standard .xlsx workbooks cannot store macros. Saving as .xlsx will erase your VBA script permanently.

  • How to Merge Multiple Sheets into One Master Sheet Using Excel VBA

    If you regularly manage workbooks with dozens of daily or monthly tabs, manually copying and pasting rows into a master summary sheet is tedious and prone to human error.

    In this guide, you’ll learn how to run a simple VBA macro that automatically combines data from all open worksheets into a single, clean Master Sheet with just one click.


    Why Automate Sheet Consolidation?

    Consolidating data across multiple tabs is a daily task in reporting, inventory management, and financial audits. Using VBA for this workflow ensures:

    • Zero Manual Mistakes: Prevents missed rows or double-pasted datasets.
    • Dynamic Row Detection: Works automatically regardless of how many rows each sheet contains.
    • Header Protection: Copies column headers only once from the first sheet.

    Step 1: Open the VBA Editor Window

    1. Open your Excel workbook containing the sheets you wish to combine.
    2. Press Alt + F11 (Option + F11 on Mac) to launch the Visual Basic Editor.
    3. In the top menu bar, click Insert ➔ Module to open a clean code window.

    Step 2: Copy and Paste the Consolidation VBA Code

    Copy the code block below and paste it directly into your blank module window:

    Sub CombineAllSheets()
        Dim ws As Worksheet
        Dim masterWs As Worksheet
        Dim lastRow As Long
        Dim masterLastRow As Long
        Dim isFirstSheet As Boolean
        
        isFirstSheet = True
        
        ' 1. Disable screen updating for faster execution
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
        
        ' 2. Delete existing "Master" sheet if it already exists
        On Error Resume Next
        Worksheets("Master").Delete
        On Error GoTo 0
        
        ' 3. Create a new "Master" sheet at the beginning
        Set masterWs = Worksheets.Add(Before:=Worksheets(1))
        masterWs.Name = "Master"
        
        ' 4. Loop through every sheet in the workbook
        For Each ws In Worksheets
            If ws.Name <> masterWs.Name Then
                lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
                
                ' Ensure sheet has data beyond row 1
                If lastRow >= 1 Then
                    If isFirstSheet Then
                        ' Copy header + data from the first worksheet
                        ws.Rows("1:" & lastRow).Copy masterWs.Range("A1")
                        isFirstSheet = False
                    Else
                        ' Find next empty row in Master sheet
                        masterLastRow = masterWs.Cells(masterWs.Rows.Count, "A").End(xlUp).Row + 1
                        ' Copy data only (skip header row 1)
                        ws.Rows("2:" & lastRow).Copy masterWs.Range("A" & masterLastRow)
                    End If
                End If
            End If
        Next ws
        
        ' 5. Auto-fit column widths on Master Sheet
        masterWs.Columns.AutoFit
        
        ' 6. Re-enable updates & show alert
        Application.ScreenUpdating = True
        Application.DisplayAlerts = True
        
        MsgBox "All sheets successfully merged into 'Master' sheet!", vbInformation, "Excel Owl Automation"
    End Sub

    Step 3: Run the Macro Using Alt + F8

    You can execute this automation right from your Excel window at any time:

    1. Switch back to your main Excel window.
    2. Press Alt + F8 (or Option + F8 on Mac) to bring up the Macro dialog box.
    3. Select CombineAllSheets from the list.
    4. Click Run.

    💡 Pro Tip: Quick Execution inside VBA Editor
    If you are actively working in the code editor, place your cursor anywhere inside the script and press F5 to run it immediately.


    Step 4: Save as Macro-Enabled Workbook (.xlsm)

    To keep your macro active for future use, save your file in the macro-enabled format:

    1. Click File ➔ Save As (or press F12).
    2. In the Save as type drop-down menu, choose Excel Macro-Enabled Workbook (*.xlsm).
    3. Click Save.

    ⚠️ Important Note: Regular .xlsx files do not support macro scripts. Saving as .xlsx will erase your VBA code permanently.

  • How to Automate Data Clean-Up in Excel Using VBA (Beginner Guide)

    If you find yourself manually deleting blank rows, trimming trailing spaces, and formatting headers every single day, Excel VBA (Visual Basic for Applications) can save you hours of repetitive work.

    In this guide, you will learn how to set up VBA for the first time and run a simple macro that automates core data clean-up tasks with just one click.


    What is an Excel Macro (VBA)?

    A Macro is a series of recorded commands or automated scripts written in VBA (Visual Basic for Applications). Think of it as a personal assistant inside Excel that executes repetitive tasks instantly without human error.


    Step 1: Open the VBA Editor Window

    1. Open your Excel workbook.
    2. Press Alt + F11 (Option + F11 on Mac) on your keyboard to open the Visual Basic Editor.
    3. In the top menu bar of the editor, click Insert ➔ Module. A blank white code window will appear.

    Step 2: Copy and Paste the VBA Code

    Copy the ENTIRE code block below (from Sub down to End Sub) and paste it directly into the blank module window:

    Sub AutomateDataCleanup()
        Dim ws As Worksheet
        Set ws = ActiveSheet
        
        ' 1. Pause screen updating to speed up code execution
        Application.ScreenUpdating = False
        
        ' 2. Trim excess spaces from all used cells
        Dim cell As Range
        For Each cell In ws.UsedRange
            If Not IsEmpty(cell.Value) Then
                cell.Value = Trim(cell.Value)
            End If
        Next cell
        
        ' 3. Auto-fit all column widths
        ws.UsedRange.Columns.AutoFit
        
        ' 4. Re-enable screen updating
        Application.ScreenUpdating = True
        
        ' 5. Completion notification
        MsgBox "Data Clean-Up Completed!", vbInformation, "Excel Owl Automation"
    End Sub

    Step 3: Run the Macro Using Alt + F8 Shortcut

    You don’t need to open the VBA Editor every time you want to clean up your data. You can run your macro directly from your Excel spreadsheet using a quick shortcut:

    1. Switch back to your main Excel sheet window.
    2. Press Alt + F8 (Option + F8 on Mac) to open the Macro Dialog Box.
    3. Select AutomateDataCleanup from the list of available macros.
    4. Click the Run button on the right.

    💡 Pro Tip: Running directly inside VBA Editor
    If you are still inside the VBA Editor code window, simply place your cursor anywhere inside the code and press F5 (or click the green Run ▶ icon at the top toolbar) to execute it immediately.


    Step 4: Save as Macro-Enabled Workbook (.xlsm)

    To ensure your new macro is preserved when you close Excel, you must save your file in a macro-enabled format:

    1. Click File ➔ Save As (or press F12).
    2. In the Save as type drop-down menu, select Excel Macro-Enabled Workbook (*.xlsm).
    3. Click Save.

    ⚠️ Important Note: Standard .xlsx files cannot store VBA scripts. If you save as a normal .xlsx workbook, your macro code will be permanently deleted!