Skip to content

VBA + Excel

VBA Code Examples

AutoMacro: VBA Add-in with 200+ Ready-To-Use VBA Code Examples & much more!

Search the list below for free Excel VBA code examples complete with explanations.
Some include downloadable files as well. These Excel VBA Macros & Scripts are professionally developed and ready-to-use.

We hope you find this list useful!

VBA Code Examples 
Basicsyes
Guide to Loops - Fors, Dos and More
If, If-Else, And, Or
Select Case
Cut, Copy, Paste from a Macro
Save File - 20 Easy Examples
Ranges and Cellsyes
Get / Set Cell Values
Select Range
Offset Range or Cell
Select All Cells
Get the active cell's Column
Change Cell Font Properties
Clear Cells
Test if Selection is Range
Merge Cells
Bold Text in a Cell
Wrap Text
Range Address
Finding the Maximum Value in Each Column in a Range
Delete All Named Ranges
Highlight Duplicates in a Range
Join Multiple Ranges
Remove Formatting For Each Cell In Range
Size an Object to a Range Size
Change a Cells Background Color
Return Column Letter of Cell
Determine Start and End Column of a Merged Cell
Macro to Autofill
Sum by Color
Rows & Columnsyes
Delete Rows that Meet Certain Criteria in VBA
Selecting Every 5th Row
Remove Blank Rows
Row Height - Column Width
Count the rows in a Selection
Count the Number of Used Rows
Autofit Columns
Select Non Contiguous Columns
Sheetsyes
Ultimate Guide to Worksheets
Activate, Select Sheet and Working with ActiveSheet
Add / Insert Worksheet
Copy Worksheet
Hide / Unhide Worksheets
Delete or Clear Worksheet
Get Sheet Name / Rename Sheet
Unprotect / Protect Worksheets
Macro to List all Sheets in a Workbook
Count the sheets in a Workbook
Hide WorkSheet Tabs
Unhide All Worksheets
Clear Entire Sheet
Macro to Create a Hyperlink Menu of Worksheets
Macro to Update all Worksheets in Workbook
Set the Default Sheet When a WorkBook Opens
Workbooksyes
Create New Workbook
Open / Close Workbook
Merge Workbooks
Filesyes
List of all files contained within a Directory
List Files in Folder
Export Range to Delimited Text File
Delete files from the hard drive
Convert Excel to CSV (Comma Delimited Text File)
VBA - Test if Workbook is Open by Workbook Name
Validate Filenames
File Exists
Copy File
Delete File
Rename File
Open File Dialog
Text and Stringsyes
Text Strings and Substrings Functions
Extract Number From String
Find the nth Word in a String
Concatenate Text(&)
New Line / Carriage Return
VBA and Vlookup: Find occurence of string
VBA Function To Calculate Number of Words in a String
Subroutine to Reverse a String
Remove Characters from Left or Right Side of Variable Length String
Loop Through a String
Add Spaces to a String - Space()
Find Text in a String (instr)
Force Proper, Upper, or Lower case automatically
Char / Chr Function
Upper, Lower, and Proper Case - Case Functions
Prevent VBA Case Sensitive
Like Operator
Logical Operators
Comparison Operators - Not Equal To and More
Compare Strings (StrComp)
Convert Text to Number
Convert Number to Text
VBA Coding Conceptsyes
Guide to Debug.Print & Immediate Window
Code Formatter Add-in
Online VBA Code Indenter
GoTo Line Label
Run a Macro Line by Line
Excel Named Ranges and Programming
Run a Macro from a Macro
Language References
Modify the right-click menu to call a macro
Benchmarking Code
VBA - Wait, Delay, Create a Timer While Running Code
Commenting
On Error Exit Sub
Option Explicit
DoEvents
Exit Sub Or Function
End All Code Execution
Eventsyes
Run Macro on Excel Open
Show or load a form when Excel starts
Run a macro when Excel closes
Run a Macro When a Cell Changes
Force a Workbook to Save
Exit Without Saving
Loopsyes
For Each Loop Examples
Exit Loop
Exit For
Settingsyes
Turn off Screen Updating
Turn Off - Turn On Calculation
Calculate Now
Status Bar Updating
VBA Turn Scroll Bars On or Off
Turn On Formula Bar - Turn Off Formula Bar
Prevent warning messages from a macro
In Depth Tutorials (Updating Soon)yes
Array Examples
Loop Through a Range
Formattingyes
Format Painter
Excel's Colour Scheme
Shapes, Charts, and Objectsyes
Guide to Charts and Graphs
Guide to Pivot Tables
Guide to Objects
Delete All Autoshapes
How to Create a Bar Chart using VBA
Tables and ListObjects
AutoFilters
UserForms & Controlsyes
Open / Close UserForm
ListBox
ComboBox
CheckBox
Spin Button
Option Button
Misc.yes
Hyperlinks
Delete Hyperlinks
Add or Remove Cell Comments from a Macro
Random Numbers
Check Spelling
Turn Off Autofilter From Code
Code or Program a Data Validation List
User Interactionyes
Yes or No Message Box
Input from a User in a Macro (InputBox)
Line Break or Line Feed in a Message Box
Viewyes
Zoom - Fit Selection
Zoom...Zoom
WorkBook Events – Don’t save with Freeze Panes
Scroll Vertically and Scroll Horizontally
Page Break Preview
Display Fullscreen
Hide Excel (The Entire Application)
ActiveWindow.WindowState
Variablesyes
Data Types - Variables and Constants
Range Variables
Global Variables
Public Variables - Use in Multiple Modules or Subs
Array Variables
Date Variable
Declare Variables - Dim
Constant Expression Required
Internetyes
Launch Internet Explorer from VBA
Advanced Programmingyes
Advanced VBA Examples
Timer Function
SendKeys
Guide to RegEx
Functionsyes
Date Functions
Check if Sheet and/or Range Exists
UDF to perform a 3-parameter Vlookup
Compare Dates
Isnumber / Isnumeric
IsEmpty / IsBlank
Round, RoundUp, RoundDown
Macro Basicsyes
Record a Macro
Editing Macros
Run a Macro
Add a button and Assign a Macro
Macros Disabled? How to Enable Macros

Ads

Excel Macro Examples

Below you will find a list of basic macro examples for common Excel automation tasks.

 

Copy and Paste a Row from One Sheet to Another

This super simple macro will copy a row from one sheet to another.

Sub Paste_OneRow()

'Copy and Paste Row
Sheets("sheet1").Range("1:1").Copy Sheets("sheet2").Range("1:1")

Application.CutCopyMode = False

End Sub

Send Email

This useful macro will launch Outlook, draft an email, and attach the ActiveWorkbook.

Sub Send_Mail()
    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .to = "test@test.com"
        .Subject = "Test Email"
        .Body = "Message Body"
        .Attachments.Add ActiveWorkbook.FullName
        .Display
    End With
    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

List All Sheets in Workbook

This macro will list all sheets in a workbook.

Sub ListSheets()
    
    Dim ws As Worksheet
    Dim x As Integer
    
    x = 1
    
    ActiveSheet.Range("A:A").Clear
    
    For Each ws In Worksheets
        ActiveSheet.Cells(x, 1) = ws.Name
        x = x + 1
    Next ws
    
End Sub

Unhide All Worksheets

This macro will unhide all worksheets.

' Unhide All Worksheets
Sub UnhideAllWoksheets()
    Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next ws
    
End Sub

Hide All Worksheets Except Active

This macro will hide all worksheets except the active worksheet.

' Hide All Sheets Except Active Sheet
Sub HideAllExceptActiveSheet()
    Dim ws As Worksheet
    
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> ActiveSheet.Name Then ws.Visible = xlSheetHidden
    Next ws
    
End Sub

Unprotect All Worksheets

This macro example will unprotect all worksheets in a workbook.

' UnProtect All Worksheets
Sub UnProtectAllSheets()
    Dim ws As Worksheet
    
    For Each ws In Worksheets
        ws.Unprotect "password"
    Next ws
    
End Sub

Protect All Worksheets

This macro will protect all worksheets in a workbook.

' Protect All Worksheets
Sub ProtectAllSheets()
    Dim ws As Worksheet
    
    For Each ws In Worksheets
        ws.protect "password"
    Next ws
    
End Sub

Delete All Shapes

This macro will delete all shapes in a worksheet.

Sub DeleteAllShapes()

Dim GetShape As Shape

For Each GetShape In ActiveSheet.Shapes
  GetShape.Delete
Next

End Sub

Delete All Blank Rows in Worksheet

This example macro will delete all blank rows in a worksheet.

Sub DeleteBlankRows()
Dim x As Long

With ActiveSheet
    For x = .Cells.SpecialCells(xlCellTypeLastCell).Row To 1 Step -1
        If WorksheetFunction.CountA(.Rows(x)) = 0 Then
            ActiveSheet.Rows(x).Delete
        End If
    Next
End With

End Sub

Highlight Duplicate Values in Selection

Use this simple macro to highlight all duplicate values in a selection.

' Highlight Duplicate Values in Selection
Sub HighlightDuplicateValues()
    Dim myRange As Range
    Dim cell As Range
    
    Set myRange = Selection
    
    For Each cell In myRange
        If WorksheetFunction.CountIf(myRange, cell.Value) > 1 Then
            cell.Interior.ColorIndex = 36
        End If
    Next cell
End Sub

Highlight Negative Numbers

This macro automates the task of highlighting negative numbers.

' Highlight Negative Numbers
Sub HighlightNegativeNumbers()
    Dim myRange As Range
    Dim cell As Range
    
    Set myRange = Selection
    
    For Each cell In myRange
        If cell.Value < 0 Then
            cell.Interior.ColorIndex = 36
        End If
    Next cell
End Sub

Highlight Alternate Rows

This macro is useful to highlight alternate rows.

' Highlight Alternate Rows
Sub highlightAlternateRows()
    Dim cell As Range
    Dim myRange As Range
    
    myRange = Selection
    
    For Each cell In myRange.Rows
        If Not Application.CheckSpelling(Word:=cell.Text) Then
            cell.Interior.ColorIndex = 36
        End If
    Next cell
End Sub

Highlight Blank Cells in Selection

This basic macro highlights blank cells in a selection.

' Highlight all Blank Cells in Selection
Sub HighlightBlankCells()
    Dim rng As Range
    
    Set rng = Selection
    rng.SpecialCells(xlCellTypeBlanks).Interior.Color = vbCyan
    
End Sub

 

Excel VBA Macros Examples - Free Download

We've created a free VBA (Macros) Code Examples add-in. The add-in contains over 100 ready-to-use macro examples, including the macro examples above!

excel vba examples free download

Excel Macro / VBA FAQs

How to write VBA code (Macros) in Excel?

To write VBA code in Excel open up the VBA Editor (ALT + F11). Type "Sub HelloWorld", Press Enter, and you've created a Macro!  OR Copy and paste one of the procedures listed on this page into the code window.

What is Excel VBA?

VBA is the programming language used to automate Excel.

How to use VBA to automate Excel?

You use VBA to automate Excel by creating Macros. Macros are blocks of code that complete certain tasks.

Practice VBA

You can practice VBA with our interactive VBA tutorial.

Automate Excel
Left Menu Icon