Professional Documents
Culture Documents
Top 100 Useful Excel Macro (VBA) Codes Examples + Free PDF Guide
Top 100 Useful Excel Macro (VBA) Codes Examples + Free PDF Guide
Macro codes can save you a ton of time. You can automate small as well as heavy task
VBA codes.
And do you know with the help of macros, you can break all the limitations of Excel wh
think Excel has?
So today, I have listed some of the useful codes examples to help you become more p
in your day to day work.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 1/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
You can use these codes even if you haven't used VBA before that. All you have to do j
these codes in your VBA editor.
These codes will exactly do the same thing which headings are telling you.
For your convenience, please follow these steps to add these codes to your workbook.
Before you use these codes, make sure you have your developer tab on your Excel rib
access VB editor.
If you don't have please use these simple steps to activate developer tab. Once you ac
developer tab, you can use below steps to paste a VBA code into VB editor.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 2/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
» On the left side in "Project Window", right click on the name of your workbook an
a new module.
» Just paste your codes into the module and close it.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 3/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
» It will show you a window with a list of the macros you have in your file. And, yo
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 4/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
First Name
Quick Navigation
Basic
These VBA codes will help you to perform some basic tasks in a flash which you frequently
your spreadsheets.
This macro code will help you to automatically add serial numbers in your excel sheet.
Once you run this macro it will show you an input box where you need to enter max n
the serial numbers and after that, it will insert numbers in the column in a sequence.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 5/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub AddSerialNumbers()
Dim i As Integer
For i = 1 To i
ActiveCell.Value = i
ActiveCell.Offset(1, 0).Activate
Next i
Last:Exit Sub
End Sub
Once you run this macro it will show an input box and you need to enter the number o
columns you want to insert.
Sub InsertMultipleColumns()
Dim i As Integer
Dim j As Integer
ActiveCell.EntireColumn.Select
For j = 1 To i
Next j
Last:Exit Sub
End Sub
[Free Download]
3. Insert Multiple Rows
E-Books Worth
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 6/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub InsertMultipleRows()
Dim i As Integer
Dim j As Integer
ActiveCell.EntireRow.Select
For j = 1 To i
Next j
Last:Exit Sub
End Sub
Quickly auto fit all the columns in your worksheet. This macro code will select all the c
your worksheet and instantly auto-fit all the columns.
Sub AutoFitColumns()
Cells.Select
Cells.EntireColumn.AutoFit
End Sub
You can use this code to auto-fit all the rows in a worksheet. When you run this code i
select all the cells in your worksheet and instantly auto-fit all the row.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 7/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub AutoFitRows()
Cells.Select
Cells.EntireRow.AutoFit
End Sub
This code will help you to remove text wrap from the entire worksheet with a single cli
It will first select all the columns and then remove text wrap and auto fit all the rows a
columns.
Sub RemoveWrapText()
Cells.Select
Selection.WrapText = False
Cells.EntireRow.AutoFit
Cells.EntireColumn.AutoFit
End Sub
7. Unmerge Cells
Select your cells and run this code and it will unmerge all the cells from the selection w
loosing data.
Sub UnmergeCells()
Selection.UnMerge
End Sub
8. Open Calculator
In window there is a specific calculator and by using this macro code you can open tha
calculator directly from Excel use for your calculations.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 8/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub OpenCalculator()
Application.ActivateMicrosoftApp Index:=0
End Sub
Use this code to add a date into the header or footer in your worksheet. You can edit t
for switching from header to footer.
Sub dateInHeader()
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = "&D"
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
ActiveWindow.View = xlNormalView
End Sub
If you want to insert a custom header then this code is for you. Run this code, enter cu
value in the input box. To change the alignment of header or footer you can edit the co
Sub customHeader()
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = myText
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 9/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
End Sub
By using this macro you can show the progress of a macro code on the status bar. This
will add serial numbers up to 5000 in your sheet and along with it will show progress o
status bar.
Sub progressStatusBar()
Cells(icntr, 1) = icntr
Application.StatusBar= " Please wait while printing the numbers " & Round((icntr/ 5000 * 100), 0) & "%"
Next
Application.StatusBar= ""
End Sub
2
Forma ing
These VBA codes will help you to format cells and ranges using some specific criteria and cond
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 10/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
This macro will check each cell of your selection and highlight the duplicate values. You
change the color from the code.
Sub HighlightDuplicateValues()
myCell.Interior.ColorIndex = 36
End If
Next myCell
End Sub
2. Go to Project Explorer (Ctrl + R, If hidden). Select your workbook & double clic
name of a particular worksheet in which you want to activate the macro.
3. Paste the code into it and select the “BeforeDoubleClick” from event drop down
Remember that, by applying this macro you will not able to edit the cell by double clic
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 11/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Target.Cells.EntireRow.Address
Range(strRange).Select
End Sub
Sub TopTen()
Selection.FormatConditions.AddTop10
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1)
.TopBottom = xlTop10Top
.Rank = 10
.Percent = False
End With
With Selection.FormatConditions(1).Font
.Color = -16752384
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13561798
.TintAndShade = 0
End With
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 12/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Selection.FormatConditions(1).StopIfTrue = False
End Sub
Sub HighlightRanges()
HighlightRange.Interior.ColorIndex = 36
Next RangeName
End Sub
Sub HighlightGreaterThanValues()
Dim i As Integer
Selection.FormatConditions.Delete
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1)
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 13/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
.Font.Color = RGB(0, 0, 0)
End With
End Sub
Sub HighlightLowerThanValues()
Dim i As Integer
Selection.FormatConditions.Delete
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
End With
End Sub
Sub highlightNegativeNumbers()
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 14/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
If WorksheetFunction.IsNumber(Rng) Then
Rng.Font.Color= -16776961
End If
End If
Next
End Sub
Sub highlightValue()
Dim I As Long
Dim J As Long
If ActiveWindow.RangeSelection.Count> 1 Then
myTxt= ActiveWindow.RangeSelection.AddressLocal
Else
myTxt= ActiveSheet.UsedRange.AddressLocal
End If
LInput: Set myRg= Application.InputBox("please select the data range:", "Selection Required", myTxt, , , , , 8)
Exit Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 15/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
End If
GoTo LInput
End If
For I = 0 To myRg.Rows.Count-1
With myRg.Range("A1").Offset(I, 0)
.Font.ColorIndex= 1
For J = 1 To Len(.Text)
.Characters(J, Len(myStr)).Font.ColorIndex= 3
Next
End With
Next I
End Sub
Sub highlightCommentCells()
Selection.SpecialCells(xlCellTypeComments).Select
Selection.Style= "Note"
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 16/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
By highlighting alternate rows you can make your data easily readable. And for this, y
use below VBA code. It will simply highlight every alternate row in selected range.
Sub highlightAlternateRows()
If rng.RowMod 2 = 1 Then
rng.Value= rng^ (1 / 3)
Else
End If
Next rng
End Sub
Sub HighlightMisspelledCells()
Next rng
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 17/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
To highlight and count all the cells in which you have an error, this code will help you.
this code and it will return a message with the number error cells and highlight all the
Sub highlightErrors()
Dim i As Integer
If WorksheetFunction.IsError(rng) Then
i = i + 1 rng.Style = "bad"
End If
Next rng
MsgBox "There are total " & i & " error(s) in this worksheet."
End Sub
Sub highlightSpecificValues()
Dim i As Integer
Dim c As Variant
If rng = c Then
rng.Style = "Note"
i=i+1
End If
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 18/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Next rng
MsgBox "There are total " & i &" "& c & " in this worksheet."
End Sub
Highlight all the Cells in a Worksheet which are Blank but hav
Invisible Space
Sometimes there are some cells which are blank but they have a single space. And, du
it’s really hard to identify them. This code will check all the cell in the worksheet and h
all the cells which have a single space.
Sub blankWithSpace()
rng.Style = "Note"
End If
Next rng
End Sub
Sub highlightMaxValue()
rng.Style = "Good"
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 19/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
End If
Next rng
End Sub
Sub highlightMinValue()
rng.Style = "Good"
End If
Next rng
End Sub
Sub highlightUniqueValues()
rng.FormatConditions.Delete
Dim uv As UniqueValues
Set uv = rng.FormatConditions.AddUniqueValues
uv.DupeUnique = xlUnique
uv.Interior.Color = vbGreen
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 20/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub columnDifference()
Range("H7:H8,I7:I8").Select
Selection.ColumnDifferences(ActiveCell).Select
Selection.Style= "Bad"
End Sub
Sub rowDifference()
Range("H7:H8,I7:I8").Select
Selection.RowDifferences(ActiveCell).Select
Selection.Style= "Bad"
End Sub
3
Printing
These macro codes will help you to automate some printing tasks which can furthe
you a ton of time.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 21/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Print Comments
Use this macro to activate settings to print cell comments in the end of the page. Let’s
have 10 pages to print, after using this code you will get all the comments on 11th las
Sub printComments()
With ActiveSheet.PageSetup
.printComments= xlPrintSheetEnd
End With
End Sub
Sub printNarrowMargin()
With ActiveSheet.PageSetup
.LeftMargin= Application
.InchesToPoints(0.25)
.RightMargin= Application.InchesToPoints(0.25)
.TopMargin= Application.InchesToPoints(0.75)
.BottomMargin= Application.InchesToPoints(0.75)
.HeaderMargin= Application.InchesToPoints(0.3)
.FooterMargin= Application.InchesToPoints(0.3)
End With
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 22/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Print Selection
This code will help you print selected range. You don't need to go to printing options a
printing range. Just select a range and run this code.
Sub printSelection()
Selection.PrintOutCopies:=1, Collate:=True
End Sub
Sub printCustomSelection()
Exit Sub
End If
Exit Sub
End If
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 23/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
4
Worksheet
These macro codes will help you to control and manage worksheets in an easy wa
save your a lot of time.
Sub HideWorksheet()
Dim ws As Worksheet
ws.Visible = xlSheetHidden
End If
Next ws
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 24/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub UnhideAllWorksheet()
Dim ws As Worksheet
ws.Visible = xlSheetVisible
Next ws
End Sub
Sub DeleteWorksheets()
Dim ws As Worksheet
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 25/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub ProtectAllWorskeets()
Dim ws As Worksheet
Dim ps As String
ws.Protect Password:=ps
Next ws
End Sub
Sub Resize_Charts()
Dim i As Integer
For i = 1 To ActiveSheet.ChartObjects.Count
With ActiveSheet.ChartObjects(i)
.Width = 300
.Height = 200
End With
Next i
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 26/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub InsertMultipleSheets()
Dim i As Integer
End Sub
Protect Worksheet
If you want to protect your worksheet you can use this macro code. All you have to do
mention your password in the code.
Sub ProtectWS()
End Sub
Unprotect Worksheet
If you want to unprotect your worksheet you can use this macro code. All you have to
mention your password which you have used while protecting your worksheet.
Sub UnprotectWS()
ActiveSheet.Unprotect "mypassword"
End Sub
Sort Worksheets
This code will help you to sort worksheets in your workbook according to their name.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 27/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub SortWorksheets()
Dim i As Integer
Dim j As Integer
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
Sheets(j).Move After:=Sheets(j + 1)
End If
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub
Sub lockCellsWithFormulas()
With ActiveSheet
.Unprotect
.Cells.Locked = False
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 28/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Protect AllowDeletingRows:=True
End With
End Sub
Sub deleteBlankWorksheets()
Dim Ws As Worksheet
Application.ScreenUpdating= False
Application.DisplayAlerts= False
If Application.WorksheetFunction.CountA(Ws.UsedRange) = 0 Then
Ws.Delete
End If
Next
Application.ScreenUpdating= True
Application.DisplayAlerts= True
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 29/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub UnhideRowsColumns()
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
End Sub
Sub SaveWorkshetAsPDF()
Dimws As Worksheet
For Each ws In Worksheetsws.ExportAsFixedFormat xlTypePDF, “ENTER-FOLDER-NAME-HERE" & ws.Name & ".pdf" Nextws
End Sub
Sub DisablePageBreaks()
Application.ScreenUpdating= False
Next Sht
Next wb
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 30/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Application.ScreenUpdating= True
End Sub
5
Workbook
These codes will help you to perform workbook level tasks in an easy way and w
minimum efforts.
Sub FileBackUp()
ThisWorkbook.name
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 31/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub CloseAllWorkbooks()
wbs.Close SaveChanges:=True
Next wb
End Sub
Sub CopyWorksheetToNewWorkbook()
ThisWorkbook.ActiveSheet.Copy _
Before:=Workbooks.Add.Worksheets(1)
End Sub
Sub Send_Mail()
With OutMail
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 32/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
.to = "Sales@FrontLinePaper.com"
.Attachments.Add ActiveWorkbook.FullName
.display
End With
End Sub
Sub OpenWorkbookAsAttachment()
Application.Dialogs(xlDialogSendMail).Show
End Sub
Welcome Message
You can use auto_open to perform a task on opening a file. All you have to do just nam
macro "auto_open".
Sub auto_open()
End Sub
Closing Message
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 33/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
You can use close_open to perform a task on opening a file. All you have to do just na
macro "close_open".
Sub auto_close()
MsgBox "Bye Bye! Don't forget to check other cool stuff on excelchamps.com"
End Sub
Sub VisibleWorkbooks()
Dim i As Integer
i=i+1
End If
Next book
MsgBox i
End Sub
6
Pivot Table
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 34/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
These codes will help you to manage and make some changes in pivot tables in a
Sub HideSubtotals()
Dim pt As PivotTable
Dim pf As PivotField
Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.name)
If pt Is Nothing Then
Exit Sub
End If
pf.Subtotals(1) = True
pf.Subtotals(1) = False
Next pf
End Sub
Sub RefreshAllPivotTables()
Dim ws As Worksheet
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 35/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Dim pt As PivotTable
pt.RefreshTable
Next pt
Next ws
End Sub
Sub UpdatePivotTableRange()
PivotName = "PivotTable2"
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 36/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Data_Sheet.Activate
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
Pivot_Sheet.PivotTables(PivotName). _
ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
Pivot_Sheet.PivotTables(PivotName).RefreshTable
'Complete Message
Pivot_Sheet.Activate
End Sub
Sub activateGetPivotData()
Application.GenerateGetPivotData = True
End Sub
Sub deactivateGetPivotData()
Application.GenerateGetPivotData = False
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 7 37/67
7
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Charts
Use these VBA codes to manage charts in Excel and save your lot of time.
Below code will convert selected chart to a clustered column chart. There are different
different types, you can find all those types from here.
Sub ChangeChartType()
ActiveChart.ChartType = xlColumnClustered
End Sub
Sub ConvertChartToPicture()
ActiveChart.ChartArea.Copy
ActiveSheet.Range("A1").Select
ActiveSheet.Pictures.Paste.Select
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 38/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub AddChartTitle()
Dim i As Variant
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Text = i
Last:
Exit Sub
End Sub
8
Advanced
Some of the codes which you can use to preform advanced task in your spreadsh
Sub SaveAsPDF()
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 39/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
End Sub
When you run this code it will create a new worksheet and create a index of workshee
hyperlink to them.
Sub TableofContent()
Dim i As Long
Application.DisplayAlerts = False
Worksheets("Table of Content").Delete
Application.DisplayAlerts = True
On Error GoTo 0
ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Worksheets(1)
For i = 1 To Sheets.Count
With ActiveSheet
.Hyperlinks.Add _
Anchor:=ActiveSheet.Cells(i, 1), _
Address:="", _
ScreenTip:=Sheets(i).Name, _
TextToDisplay:=Sheets(i).Name
End With
Next i
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 40/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub PasteAsPicture()
Application.CutCopyMode = False
Selection.Copy
ActiveSheet.Pictures.Paste.Select
End Sub
Sub LinkedPicture()
Selection.Copy
ActiveSheet.Pictures.Paste(Link:=True).Select
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 41/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub Speak()
Selection.Speak
End Sub
Sub DataForm()
ActiveSheet.ShowDataForm
End Sub
Sub GoalSeekVBA()
.GoalSeek_ Goal:=Target, _
ChangingCell:=Range("C2")
End With
Exit Sub
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 42/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
9
Formulas
These codes will help you to calculate or get results which often you do with work
functions and formulas.
Simply convert formulas into values. When you run this macro it will quickly change th
formulas into absolute values.
Sub ConvertToValues()
Select Case MsgBox("You Can't Undo This Action. " & "Save Workbook First?", vbYesNoCancel, "Alert")
Case Is = vbYes
ThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
If MyCell.HasFormula Then
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 43/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
MyCell.Formula = MyCell.Value
End If
Next MyCell
End Sub
One of the most useful macros from this list. It will check your selection and then rem
the extra spaces from that.
Sub RemoveSpaces()
Select Case MsgBox("You Can't Undo This Action. " & "Save Workbook First?", _
vbYesNoCancel, "Alert")
Case Is = vbYesThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
myCell = Trim(myCell)
End If
Next myCell
End Sub
Simply remove characters from the starting of a text string. All you need is to refer to
insert a text into the function and number of characters to remove from the text string
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 44/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
t has two arguments "rng" for the text string and "cnt" for the count of characters to r
For example: If you want to remove first characters from a cell, you need to enter 1 in
End Function
Let’s say you have a list of numbers in a column and you want to add degree symbol w
them.
Sub degreeSymbol()
rng.Select
If IsNumeric(ActiveCell.Value) Then
End If
End If
Next
End Sub
Reverse Text
All you have to do just enter "rvrse" function in a cell and refer to the cell in which you
text which you want to reverse.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 45/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
rvrse = VBA.strReverse(cell.Value)
End Function
This macro code will help you to activate R1C1 reference style without using Excel opt
Sub ActivateR1C1()
Application.ReferenceStyle = xlR1C1
Else
Application.ReferenceStyle = xlR1C1
End If
End Sub
This macro code will help you to activate A1 reference style without using excel option
Sub ActivateA1()
Application.ReferenceStyle = xlA1
Else
Application.ReferenceStyle = xlA1
End If
End Sub
Insert Timestamp
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 46/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
With this code, you can insert a timestamp in sequence from 00:00 to 23:00
Sub TimeStamp()
Dim i As Integer
For i = 1 To 24
ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select
Next i
End Sub
If you have dates in your worksheet and you want to convert all those dates into days
code is for you. Simply select the range of cells and run this macro.
Sub date2day()
Selection.Value = Selection.Value
With tempCell
.Value = Day(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 47/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub date2year()
Selection.Value = Selection.Value
With tempCell
.Value = Year(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub
If you have time with the date and you want to remove it then you can use this code.
Sub removeTime()
Rng.Value = VBA.Int(Rng.Value)
End If
Next
Selection.NumberFormat = "dd-mmm-yy"
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 48/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub removeDate()
End If
End Sub
Select the cells and run this code. It will check each and every cell of selected range a
convert it into upper case text.
Sub convertUpperCase()
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value = UCase(Rng)
End If
Next
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 49/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
This code will help you to convert selected text into lower case text. Just select a rang
where you have text and run this code. If a cell has a number or any value other than
value will remain same.
Sub convertLowerCase()
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value= LCase(Rng)
End If
Next
End Sub
And, this code will convert selected text into the proper case where you have the first
capital and rest in small.
Sub convertProperCase()
If WorksheetFunction.IsText(Rng) Then
Rng.Value= WorksheetFunction.Proper(Rng.Value)
End If
Next
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 50/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
In text case, you have the first letter of the first word in capital and rest all in words in
a single sentence. And, this code will help you convert normal text into sentence case.
Sub convertTextCase()
If WorksheetFunction.IsText(Rng) Then
End If
Next rng
End Sub
To remove a particular character from a selected cell you can use this code. It will show
input box to enter the character you want to remove.
Sub removeChar()
Dim rc As String
Next
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 51/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub Word_Count_Worksheet()
Dim S As String
Dim N As Long
S = Application.WorksheetFunction.Trim(rng.Text)
N=0
End If
WordCnt = WordCnt + N
Next rng
MsgBox "There are total " & Format(WordCnt, "#,##0") & " words in the active worksheet"
End Sub
If you have numeric data where you have an apostrophe before each number, you run
to remove it.
Sub removeApostrophes()
Selection.Value = Selection.Value
End Sub
This code will simply help you to remove all the decimals from the numbers from the s
range.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 52/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub removeDecimals()
rng.Value= Int(rng)
rng.NumberFormat= "0"
Next rng
End Sub
Let’s you have a list of numbers and you want to multiply all the number with a particu
use this code.
Select that range of cells and run this code. It will first ask you for the number with wh
want to multiple and then instantly multiply all the numbers with it.
Sub multiplyWithNumber()
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng * c
Else
End If
Next rng
End Sub
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 53/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Just like multiplying you can also add a number into a set of numbers.
Sub addNumber()
DimiAs Integer
If WorksheetFunction.IsNumber(rng) Then
rng.Value= rng+ i
Else
End If
Next rng
End Sub
To calculate square root without applying a formula you can use this code. it will simpl
all the selected cells and convert numbers to their square root.
Sub getSquareRoot()
Dim i As Integer
If WorksheetFunction.IsNumber(rng) Then
rng.Value= Sqr(rng)
Else
End If
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 54/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Next rng
End Sub
To calculate cube root without applying a formula you can use this code. It will simply
the selected cells and convert numbers to their cube root.
Sub getCubeRoot()
Dimi As Integer
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng ^ (1 / 3)
Else
End If
Nextrng
End Sub
Just like serial numbers you can also insert alphabets in your worksheet. Beloware the
which you can use.
Sub addcAlphabets()
Dim i As Integer
For i= 65 To 90
ActiveCell.Value= Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 55/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
End Sub
Sub addsAlphabets()
Dim i As Integer
For i= 97 To 122
ActiveCell.Value= Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
End Sub
Sometimes it’s really hard to understand Roman numbers as serial numbers. This code
you to convert roman numbers into arabic numbers.
Sub convertToNumbers()
Selection.Value= Selection.Value
rng.Value= WorksheetFunction.Arabic(rng)
End If
Next rng
End Sub
This code will simply check all the cell in the selection and convert all the negative num
positive. Just select a range and run this code.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 56/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Sub removeNegativeSign()
Selection.Value= Selection.Value
If WorksheetFunction.IsNumber(rng)
End If
Next rng
End Sub
For data where you have blank cells, you can add zeros in all those cells. It makes eas
formula and use those cells in further calculations.
Sub replaceBlankWithZero()
Selection.Value= Selection.Value
rng.Value= "0"
Else
End If
Next rng
End Sub
Conclusion
I use some of these codes every day to increase my productivity. And, I’m sure it will a
you in your work.
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 57/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
But, you have to help me to update this list. If you have any useful code which you us
to save your time, please share with me in the comment section, I’d love to hear from
And please don’t forget to share this list with your friends.
Share Tweet
2. 8 Simple Steps to Use VBA to Create a Pivot Table In Excel [Macro Code]
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 58/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Automate Your Pivot How to Use Data Entry VBA Archives How to Group
Table With VBA [Step Form in Excel to Enter a Pivot Table B
By Step Guide] Data in Table [No... Quarter, Month
3 Steps To Create a Follow these Steps to Top 100 Excel Secret Is Out -
Pivot Table using Add Developer Tab in Functions with Bar-Code In E
Multiple Files with... Excel [Windows + Mac] Examples + Sample...
80 Keyboard Shortcuts
“Your excel book is immensely helpful. Thank you for sharing it. Much appreciated.” - Joseph Gabriella (Japa
Your Name
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 59/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Your email i
51 Comments ExcelChamps.com
So
Recommend 4 ⤤ Share
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
Thanks
△ ▽ • Reply • Share ›
Sub InsertMultipleRows()
Dim i As Integer
Dim j As Integer
Rows("35:35").Select
On Error GoTo Last
i = InputBox("Enter number of items to add", "Insert Items")
For j = 1 To i
Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove
Next j
Last:
Range("H34").Select
Selection.AutoFill Destination:=Range("H34:H35"), Type:=xlFillDefault
'Range("H34"+i).Select (This is the part I need help with)
Range("C35").Select
Exit Sub
End Sub
△ ▽ • Reply • Share ›
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 62/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
△ ▽ • Reply • Share ›
I was also trying to get in touch with you to understand if there is a way we can filter a table based on u
Let’s say we have the following table on the meetings done by a person, and the start time of each mee
△ ▽ • Reply • Share ›
>
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 64/67
4/15/2018 Top 100 Useful Excel Macro [VBA] Codes Examples + Free PDF Guide
Pravin Bhaiswar > Puneet Gogia • 6 months ago
Sir, I used this code at my office...it was nice working but on my home pc..it says "Run tim
Invalid procedure call or argument.......So please have solution sir.
△ ▽ • Reply • Share ›
I want to learn how to create macro. I have the basic knowledge of VB. Please advise from where shou
△ ▽ • Reply • Share ›
Rather than a PDF, how about putting this tips in a downloadable spreadsheet or Word document that t
be sorted by insertion date as well as category. Actually. If you make the download cumulative that wou
better. So each month we could replace the old file with the new one, containing the all of the tips you'v
here over time. Even if you start now building the cumulative file, that would be better.
△ ▽ • Reply • Share ›
2. Closing Message
“You can use close_open to perform a task on opening a file. All you have to do just name your macro
"close_open".”
Sub auto_close()
The name of the macro is not “close_open”
3. Count/Highlight Cells With Error In Entire Worksheet
These statements must be in different lines:
i = i + 1 rng.Style = "bad"
4. In Count/Highlight Cells With A Specific In Entire Worksheet please add the word “Value” after “Spec
△ ▽ • Reply • Share ›
Sub HighlightAlternateRows ()
Dim rng As Range
__For Each rng In Selection.Rows
____If rng.Row Mod 2 = 1 Then
____rng.Style = "20% - Accent1"
____End If
__Next rng
End Sub
ALSO ON EXCELCHAMPS.COM
highlight duplicate values using vba Conditional Ranking in Excel using SUMP
2 comments • 8 months ago Function [RANKIF]
Ron007 — oops, the page is broken. All I see is the title, 7 comments • 8 months ago
and the graphic. No body text and no advertising ... Gary Evans — Brilliant post. I have a similar
I can't solve, maybe you can help.I have a co
has many runs (1,2,3,4 and 1,2,3 and 1,2,3,4
How to Create a Data Validation with Date Range How to Calculate SQUARE ROOT in Exce
3 comments • 7 months ago Symbol]
VIPUL SHAH — SORRY IT IS NOT DATE IT IS DATA I 2 comments • 5 months ago
NEED TO INSERT ADDITIONAL ITEMS ROWS IF I Puneet Gogia — Yes, you are quite right on t
REQUIRE FOR MY ESTIMATE
https://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 67/67