Tag: VBA tutorial

  • 10 Useful VBA Macros to Automate Repetitive Tasks in Excel for Faster Productivity

    Microsoft Excel is one of the most powerful tools for data analysis, reporting, and automation. However, as data grows, repetitive tasks like formatting, copying data, generating reports, and cleaning datasets consume valuable time. This is where VBA (Visual Basic for Applications) comes to the rescue.

    VBA allows you to automate repetitive Excel tasks using small pieces of code called macros. From simple formatting to complex workflows, VBA can handle thousands of actions within seconds — saving you hours of manual effort.

    In this detailed article, we’ll explore 10 highly useful VBA macros that every Excel user should know to improve efficiency, accuracy, and productivity. Each example includes code, explanation, and practical use cases.


    What is VBA in Excel?

    VBA (Visual Basic for Applications) is Microsoft’s event-driven programming language integrated into Excel and other Office applications. It enables users to control Excel’s functionality programmatically — from automating keystrokes and formulas to creating custom functions and dashboards.

    When you create or record a macro, Excel stores it in the VBA editor, which you can access using ALT + F11. These macros can be triggered by a shortcut, a button, or even automatically on file opening.

    According to internal surveys among data professionals, using VBA can reduce manual Excel work by up to 70% and improve report generation time by more than 60% in routine office operations.


    Benefits of Using VBA Macros

    1. Saves Time: Repetitive tasks that take hours can be completed in seconds.
    2. Reduces Errors: Automation ensures consistency and accuracy in data handling.
    3. Increases Productivity: Frees up time for analysis and decision-making.
    4. Customizable: You can tailor macros for specific workflows.
    5. Scalable: VBA scripts can handle large datasets efficiently.

    For example, imagine you format 20 sheets daily in a report file — a 10-line VBA macro can finish that job instantly.


    Table: 10 Most Useful VBA Macros for Excel Automation

    Macro Name / FunctionPurpose
    1. Auto Format Data RangeQuickly format and clean large datasets
    2. Insert Current Date & TimeAuto-insert date/time in selected cells
    3. Highlight Duplicate ValuesIdentify duplicates instantly
    4. Automatically Save WorkbookSet auto-save interval
    5. Delete Blank RowsClean unused blank rows from data
    6. Protect All SheetsLock all sheets at once
    7. Send Email from ExcelAutomate Outlook email sending
    8. Create Backup CopyCreate automatic backup of workbook
    9. Combine Multiple SheetsMerge data from all sheets into one
    10. Auto Refresh Pivot TableRefresh all Pivot Tables instantly

    1. Auto Format Data Range

    When working with raw data, manual formatting consumes time. This macro automatically applies formatting such as font, borders, and alignment.

    Sub AutoFormatData()
        Dim rng As Range
        Set rng = Selection
        With rng
            .Font.Name = "Calibri"
            .Font.Size = 11
            .EntireColumn.AutoFit
            .Borders.LineStyle = xlContinuous
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlCenter
        End With
    End Sub
    

    Use Case: Apply consistent formatting across sales, HR, or finance reports instantly.


    2. Insert Current Date & Time Automatically

    You can quickly insert a timestamp in the active cell using VBA. This is especially helpful for logging updates or creating time-based reports.

    Sub InsertDateTime()
        ActiveCell.Value = Now
        ActiveCell.NumberFormat = "dd-mmm-yyyy hh:mm:ss"
    End Sub
    

    Use Case: Keep automatic time records in project tracking or data entry sheets.


    3. Highlight Duplicate Values

    Identifying duplicate entries manually is tedious. The below VBA macro automatically highlights duplicate cells in a selected range.

    Sub HighlightDuplicates()
        Dim Rng As Range, Cell As Range
        Set Rng = Selection
        For Each Cell In Rng
            If WorksheetFunction.CountIf(Rng, Cell.Value) > 1 Then
                Cell.Interior.Color = vbYellow
            End If
        Next Cell
    End Sub
    

    Use Case: Data cleaning in customer records, employee lists, or product catalogs.


    4. Automatically Save Workbook

    Forgetting to save changes can cause data loss. This macro saves your workbook every 5 minutes automatically.

    Sub AutoSaveWorkbook()
        Application.OnTime Now + TimeValue("00:05:00"), "AutoSaveWorkbook"
        ThisWorkbook.Save
    End Sub
    

    Use Case: Continuous backup during data entry or report building sessions.


    5. Delete Blank Rows in Worksheet

    Blank rows make data messy and increase file size. This macro removes all blank rows in the selected worksheet efficiently.

    Sub DeleteBlankRows()
        Dim Rng As Range
        On Error Resume Next
        Set Rng = Range("A1").CurrentRegion
        Rng.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    End Sub
    

    Use Case: Clean up imported or exported data instantly without filters.


    6. Protect All Sheets in Workbook

    Instead of manually protecting each worksheet, this VBA macro locks all sheets with a single password.

    Sub ProtectAllSheets()
        Dim ws As Worksheet
        Dim Pwd As String
        Pwd = "admin123"
        For Each ws In ThisWorkbook.Worksheets
            ws.Protect Password:=Pwd
        Next ws
    End Sub
    

    Use Case: Protect reports and dashboards before sharing with clients or teams.


    7. Send Email Directly from Excel

    Automate email sending through Outlook without manually composing messages.

    Sub SendEmail()
        Dim OutlookApp As Object
        Dim OutlookMail As Object
        Set OutlookApp = CreateObject("Outlook.Application")
        Set OutlookMail = OutlookApp.CreateItem(0)
        
        With OutlookMail
            .To = "receiver@domain.com"
            .Subject = "Monthly Sales Report"
            .Body = "Please find the attached report."
            .Attachments.Add "C:\Reports\Sales.xlsx"
            .Send
        End With
    End Sub
    

    Use Case: Automatically send sales reports or invoices every month.


    8. Create a Backup Copy of the Workbook

    This macro creates a timestamped backup copy every time you run it.

    Sub CreateBackup()
        Dim FilePath As String
        FilePath = ThisWorkbook.Path & "\Backup_" & Format(Now, "yyyymmdd_hhmmss") & ".xlsm"
        ThisWorkbook.SaveCopyAs FilePath
        MsgBox "Backup Created Successfully!"
    End Sub
    

    Use Case: Keep multiple backup versions of financial or operational data.


    9. Combine Data from Multiple Sheets

    If you have multiple sheets with similar structure, this macro merges all into one summary sheet.

    Sub CombineSheets()
        Dim ws As Worksheet
        Dim Summary As Worksheet
        Dim lr As Long, NextRow As Long
        Set Summary = Sheets.Add
        Summary.Name = "CombinedData"
        
        For Each ws In ThisWorkbook.Worksheets
            If ws.Name <> Summary.Name Then
                lr = ws.Cells(Rows.Count, 1).End(xlUp).Row
                ws.Range("A1:A" & lr).EntireRow.Copy
                Summary.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
            End If
        Next ws
        Application.CutCopyMode = False
        MsgBox "Data Combined Successfully!"
    End Sub
    

    Use Case: Combine regional or departmental reports into a master summary in seconds.


    10. Auto Refresh All Pivot Tables

    Refreshing multiple Pivot Tables manually can be time-consuming. This macro updates all Pivot Tables at once.

    Sub RefreshAllPivots()
        Dim ws As Worksheet
        Dim pt As PivotTable
        For Each ws In ThisWorkbook.Worksheets
            For Each pt In ws.PivotTables
                pt.RefreshTable
            Next pt
        Next ws
        MsgBox "All Pivot Tables Refreshed!"
    End Sub
    

    Use Case: Update dashboards or MIS reports instantly after new data upload.


    Best Practices for VBA Automation

    1. Always save a backup before running VBA scripts on important data.
    2. Use Option Explicit to catch variable errors early.
    3. Keep macros in a Personal Macro Workbook for universal access.
    4. Assign keyboard shortcuts or buttons for frequent use.
    5. Document macros with comments for future reference.
    6. Schedule automatic VBA triggers with Workbook_Open or Worksheet_Change events.

    Performance and Security Facts

    • A single VBA macro can replace hundreds of manual keystrokes.
    • On average, Excel users report 30–50% time savings using custom macros.
    • Password-protected macros help ensure data security and prevent accidental changes.
    • VBA supports error-handling routines, improving automation reliability.

    VBA has been used in industries like banking, manufacturing, and logistics to generate automated daily reports that otherwise required hours of manual labor.


    Conclusion

    Excel VBA macros are not just time-savers — they are productivity multipliers. Whether it’s cleaning data, protecting sheets, or generating automated reports, VBA can handle nearly every repetitive task with ease.

    The 10 VBA macros shared above can serve as a foundation to build your automation library and transform how you use Excel. Once you start leveraging VBA, you’ll notice faster workflows, fewer errors, and more efficient reporting.

    As your experience grows, you can expand these macros into custom dashboards, automated reports, and even data-driven decision systems within Excel.


    Disclaimer

    The VBA codes and examples shared in this article are for educational purposes only. Users should test all macros on sample data before applying them to live or sensitive files. The author is not responsible for any unintended data loss or formatting changes caused by improper use.


  • Extract Numbers from Text in Excel Using VBA – Works for Indian & European Formats

    🧾 Scenario:

    At Shree Tech Pvt. Ltd., Priya is a finance executive handling a lot of messy Excel data received from multiple vendors and sales teams across India and Europe.

    One day, she encounters a peculiar problem.
    In the “Remarks” column, instead of clean numbers, she sees entries like:

    • "₹3,499 paid in full"
    • "1.250,50 EUR"
    • "Advance of 7500.00 received"
    • "Amount is Rs. 2,50,000/-"

    She needs to extract only the numeric value from these cells, but Excel’s built-in tools can’t help much.

    That’s when her teammate, Rohit, a skilled MIS guy, steps in with a magic wand—a custom VBA function called getNumber.


    🧙‍♂️ The Magic VBA Function: getNumber

    Here’s the full code Rohit shares:

    vbaCopyEditPublic Function getNumber(fromThis As Range) As Double
        'Extract the number from a cell and return it.
        Dim retVal As String
        Dim ltr As String, i As Integer, european As Boolean
        
        retVal = ""
        getNumber = 0
        european = False
        
        On Error GoTo last
        'Check if the range contains European format number i.e. , for decimal point
        If fromThis.Value Like "*.*,*" Then
            european = True
        End If
        
        For i = 1 To Len(fromThis)
            ltr = Mid(fromThis, i, 1)
            If IsNumeric(ltr) Then
                retVal = retVal & ltr
            ElseIf ltr = "." And (Not european) And Len(retVal) > 0 Then
                retVal = retVal & ltr
            ElseIf ltr = "," And european And Len(retVal) > 0 Then
                retVal = retVal & "."
            End If
        Next i
        getNumber = CDbl(retVal)
    last:
    End Function
    

    🔍 Line-by-Line Breakdown with Office-style Explanation


    ✅ What it does:

    Extracts numbers embedded in any text, whether the number is in Indian format (e.g., 2,50,000) or European format (e.g., 1.234,56).


    🎬 Scene-by-Scene Breakdown:


    🪪 Characters:

    • fromThis: The Excel cell that has the mixed content (like "Total ₹4,500.50 paid").
    • retVal: The string variable used to slowly build the extracted number.
    • european: A flag to detect if commas are used as decimal separators (common in European format like "1.234,56").

    💡 Step 1: Initialization

    vbaCopyEditretVal = ""
    getNumber = 0
    european = False
    

    Rohit clears any previous values and sets the assumption that the format is not European by default.


    🧠 Step 2: Detecting European Format

    vbaCopyEditIf fromThis.Value Like "*.*,*" Then
        european = True
    End If
    

    This checks if the cell contains both a dot and a comma (e.g., "1.234,56"). If yes, it assumes the comma is the decimal point (European format).

    Priya’s vendor from Germany sent "1.250,50 EUR". This line sets european = True.


    🔁 Step 3: Loop Through Each Character

    vbaCopyEditFor i = 1 To Len(fromThis)
        ltr = Mid(fromThis, i, 1)
    

    The loop reads the text character by character. If the cell has "Amount ₹2,50,000.75", it starts reading "A", "m", "o", etc.


    🔢 Step 4: Build the Numeric Part

    Here’s the logic Rohit uses:

    vbaCopyEditIf IsNumeric(ltr) Then
        retVal = retVal & ltr
    

    If the character is a digit (0–9), it adds to the final number string.

    Then:

    vbaCopyEditElseIf ltr = "." And (Not european) And Len(retVal) > 0 Then
        retVal = retVal & ltr
    

    If it’s a . and it’s not European format, it’s added as the decimal point.

    vbaCopyEditElseIf ltr = "," And european And Len(retVal) > 0 Then
        retVal = retVal & "."
    

    If it’s European format, then the comma , is converted into a dot .—because VBA/Excel understand . as the decimal point.

    So "1.234,56" becomes "1234.56" internally.


    💾 Step 5: Convert the Final String to Number

    vbaCopyEditgetNumber = CDbl(retVal)
    

    Finally, the retVal string, say "4500.75", is converted into a Double data type using CDbl.


    🛑 Step 6: Error Handling

    vbaCopyEditOn Error GoTo last
    ...
    last:
    End Function
    

    If there’s any weird data or unexpected character that crashes the function, it fails silently and exits.


    📦 Examples: How It Works in Practice

    Cell ContentOutputExplanation
    "Rs. 4,500.75 paid"4500.75Indian format, plain extraction
    "1.234,56 EUR"1234.56European format, comma → dot
    "Amount: ₹2,50,000/-"250000Only digits picked, commas ignored
    "Advance of 7500.00 received"7500.00Straight number pulled out
    "Zero balance"0No digits found, returns 0

    ✅ Where to Use This Function

    Use =getNumber(A2) in any cell, where A2 contains your text with numbers.


    🎁 Bonus Tip from Rohit:

    You can paste this VBA code into your Excel file by pressing:

    1. ALT + F11 → Open VBA editor
    2. Insert > Module
    3. Paste the code
    4. Save as Macro-Enabled Workbook (.xlsm)

    Download Number Extraction VBA Function File