What is a Macro Code?
In MS Excel, macro code is a programming code which is written in VBA (Visual Basic for Applications) language.
The idea is to use macro code for automating various activities which you perform manually in Excel, otherwise.
For example, you can use a code to print only a particular range of cells just with a single click instead of selecting the range -> File Tab -> Print -> Print Select -> OK Button.
How to use a Macro Code in Excel
Before you use excel VBA codes, make sure you have your developer tab on your Excel ribbon to access VBA editor. Once you activate developer tab you can follow below steps to paste a VBA code into VBA editor.
- Go to your developer tab and click on “Visual Basic” to open the Visual Basic Editor.
- On the left side in “Project Window”, right click on the name of your workbook and insert a new module.
- Just paste your code into the module and close it.
- Now, go to your developer tab and click on the macro button.
- It will show you a window with a list of the macros you have in your file from where you can run a macro from that list.
List of Top 100 macro Examples (CODES) for VBA beginners
I have added all the codes into specific categories so that you can find your favorite codes quickly. Just read the title and click on it to get the code.
Table of Contents
Basic VBA Macro Codes in Excel
Custom Header & Footer
Sub CustomHeader() Dim myText As String myText = InputBox(“Enter your …
Add Header and Footer Date
Sub DateInHeader() With ActiveSheet.PageSetup .LeftHeader = “” .CenterHeader = “&D” …
Unmerge Cells
Sub UnmergeCells() Selection.UnMerge End Sub Unmerge Cells code simply uses …
Open Calculator
Sub OpenCalculator() Application.ActivateMicrosoftApp Index:=0 End Sub In Windows, there is …
Auto Fit Rows
Sub AutoFitRows() Cells.Select Cells.EntireRow.AutoFit End Sub You can use this …
Remove Text Wrap
Sub RemoveTextWrap() Range(“A1”).WrapText = False End Sub This code will …
Auto Fit Columns
Sub AutoFitColumns() Cells.Select Cells.EntireColumn.AutoFit End Sub Use above Excel macro …
Insert Multiple Columns
Sub InsertMultipleColumns() Dim i As Integer Dim j As Integer …
Formatting VBA Macro Codes in Excel
Highlight Greater than Values
Sub HighlightGreaterThanValues() Dim i As Integer i = InputBox(“Enter Greater …
Highlight Lower Than Values
Sub HighlightLowerThanValues() Dim i As Integer i = InputBox(“Enter Lower …
Highlight Negative Numbers
Sub highlightNegativeNumbers() Dim Rng As Range For Each Rng In …
Highlight Alternate Rows in the Selection
Sub highlightAlternateRows() Dim rng As Range For Each rng In …
Highlight Cells With Error in the Entire Worksheet
Sub highlightErrors() Dim rng As Range Dim i As Integer …
Highlight Cells with Misspelled Words
Sub HighlightMisspelledCells() Dim rng As Range For Each rng In …
Highlight Cells with a Specific Text in Worksheet
Sub highlightSpecificValues() Dim rng As range Dim i As Integer …
Highlight all Blank Cells Invisible Space
Sub blankWithSpace() Dim rng As Range For Each rng In …
Highlight Named Ranges
Sub HighlightRanges() Dim RangeName As Name Dim HighlightRange As Range …
Chart VBA Macro Codes in Excel
Paste Chart as an Image
Sub ConvertChartToPicture() ActiveChart.ChartArea.Copy ActiveSheet.Range(“A1”).Select ActiveSheet.Pictures.Paste.Select End Sub Paste Chart as …
Change Chart Type
Sub ChangeChartType() ActiveChart.ChartType = xlColumnClustered End Sub This code will …
Formula VBA Macro Codes in Excel
Activate R1C1 Reference Style
Sub ActivateR1C1() If Application.ReferenceStyle = xlA1 Then Application.ReferenceStyle = xlR1C1 …
Activate A1 Reference Style
Sub ActivateA1() If Application.ReferenceStyle = xlR1C1 Then Application.ReferenceStyle = xlA1 …
Add Insert Degree Symbol in Excel
Sub degreeSymbol( ) Dim rng As Range For Each rng …
Remove Characters from a String
Public Function removeFirstC(rng As String, cnt As Long) removeFirstC = …
Remove Spaces from Selected Cells
Sub RemoveSpaces() Dim myRange As Range Dim myCell As Range …
Word Count from Entire Worksheet
Sub Word_Count_Worksheet() Dim WordCnt As Long Dim rng As Range …
Remove Decimals from Numbers
Sub removeDecimals() Dim lnumber As Double Dim lResult As Long …
Pivot Table VBA Macro Codes in Excel
Disable/Enable Get Pivot Data
Sub activateGetPivotData() Application.GenerateGetPivotData = True End Sub Sub deactivateGetPivotData() Application.GenerateGetPivotData …
Refresh All Pivot Tables
ub vba_referesh_all_pivots() Dim pt As PivotTable For Each pt In …
Auto Update Pivot Table Range
Sub UpdatePivotTableRange() Dim Data_Sheet As Worksheet Dim Pivot_Sheet As Worksheet …
Hide Pivot Table Subtotals thru VBA
Sub HideSubtotals() Dim pt As PivotTable Dim pf As PivotField …
Printing VBA Macro Codes in Excel
Print Custom Pages
Sub printCustomSelection() Dim startpage As Integer Dim endpage As Integer …
Print Selection
Sub printSelection() Selection.PrintOut Copies:=1, Collate:=True End Sub Excel Macro code …
Print Narrow Margin
Sub printNarrowMargin() With ActiveSheet.PageSetup .LeftMargin = Application .InchesToPoints (0.25) .RightMargin …
Print Comments
Print Comments Sub printComments() With ActiveSheet.PageSetup .printComments = xlPrintSheetEnd End …
Workbook VBA Macro Codes in Excel
Add Workbook to a Mail Attachment
Sub OpenWorkbookAsAttachment() Application.Dialogs(xlDialogSendMail).Show End Sub Add Workbook to a Mail …
Close all Workbooks at Once
Sub CloseAllWorkbooks() Dim wbs As Workbook For Each wbs In …
Count Open Unsaved Workbooks
Count Open Unsaved Workbooks. Sub VisibleWorkbooks() Dim book As Workbook …
Active Workbook in an Email
Sub Send_Mail() Dim OutApp As Object Dim OutMail As Object …
Copy Active Worksheet into a New Workbook
Sub CopyWorksheetToNewWorkbook() ThisWorkbook.ActiveSheet.Copy _ Before:=Workbooks.Add.Worksheets(1) End Sub Copy Active Worksheet …
Create a Backup of a Current Workbook
Sub FileBackUp() ThisWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & _ “” & Format(Date, “mm-dd-yy”) …
Worksheet VBA Macro Codes in Excel
Unhide all Rows and Columns
Sub UnhideRowsColumns() Columns.EntireColumn.Hidden = False Rows.EntireRow.Hidden = False End Sub …
Save Each Worksheet as a Single PDF
Sub SaveWorkshetAsPDF() Dimws As Worksheet For Each ws In Worksheets …
Delete all Blank Worksheets
Sub deleteBlankWorksheets() Dim Ws As Worksheet On Error Resume Next …
Protect all the Cells With Formulas
Sub lockCellsWithFormulas() With ActiveSheet .Unprotect .Cells.Locked = False .Cells.SpecialCells(xlCellTypeFormulas).Locked = …
Disable Page Breaks
Sub DisablePageBreaks() Dim wb As Workbook Dim wks As Worksheet …
Protect Worksheet
Sub ProtectWS() ActiveSheet.Protect “mypassword”, True, True End Sub If you …
UnProtect Worksheet
Sub UnprotectWS() ActiveSheet.Unprotect “mypassword” End Sub UnProtect Worksheet If you …
Insert Multiple Worksheets
Sub InsertMultipleSheets() Dim i As Integer i = _ InputBox(“Enter …
Advance VBA Macro Codes in Excel
VBA Code to Search on Google
Sub SearchWindow32() Dim chromePath As String Dim search_string As String …
Activate Data Entry Form
Sub DataForm() ActiveSheet.ShowDataForm End Sub There is a default data entry …
Insert a Linked Picture
Sub LinkedPicture() Selection.Copy ActiveSheet.Pictures.Paste(Link:=True).Select End Sub How to Insert a …
Convert Range into an Image
Sub PasteAsPicture() Application.CutCopyMode = False Selection.Copy ActiveSheet.Pictures.Paste.Select End Sub How …
Save Selected Range as a PDF
Sub HideSubtotals() Dim pt As PivotTable Dim pf As PivotField …