Macros For Excel
Macros For Excel
Once you run this macro it will show you an input box where you need to enter max
number for the serial numbers and after that, it will insert numbers in the column
in a sequence.
Sub AddSerialNumbers()
Dim i As Integer
On Error GoTo Last
i = InputBox("Enter Value", "Enter Serial Numbers")
For i = 1 To i
ActiveCell.Value = i
ActiveCell.Offset(1, 0).Activate
Next i
Last:Exit Sub
End Sub
2. Insert Multiple Columns
Once you run this macro it will show an input box and you need to enter the number
of 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
Sub InsertMultipleRows()
Dim i As Integer
Dim j As Integer
ActiveCell.EntireRow.Select
For j = 1 To i
Selection.Insert Shift:=xlToDown,
CopyOrigin:=xlFormatFromRightorAbove
Next j
Last:Exit Sub
End Sub
This macro code will select all the cells in your worksheet and instantly auto-fit
all the columns.
Sub AutoFitColumns()
Cells.Select
Cells.EntireColumn.AutoFit
End Sub
When you run this code it will select all the cells in your worksheet and instantly
auto-fit all the row.
Sub AutoFitRows()
Cells.Select
Cells.EntireRow.AutoFit
End Sub
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 un-merge all the cells from the
selection with your 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
that calculator directly from Excel use for your calculations.
Sub OpenCalculator()
Application.ActivateMicrosoftApp Index:=0
End Sub
You can edit this code 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
Run this code, enter custom value in the input box. To change the alignment of
header or footer you can edit the code.
Sub customHeader()
.LeftHeader = ""
.CenterHeader = myText
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
End Sub
Formatting Codes
These VBA codes will help you to format cells and ranges using some specific
criteria and conditions.
Sub HighlightDuplicateValues()
myCell.Interior.ColorIndex = 36
End If
Next myCell
End Sub
Cancel As Boolean)
Target.Cells.EntireRow.Address
Range(strRange).Select
End Sub
Sub TopTen()
Selection.FormatConditions.AddTop10
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
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
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.Add Type:=xlCellValue,
Operator:=xlGreater, Formula1:=i
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
End With
End Sub
Dim i As Integer
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue,
Operator:=xlLower, Formula1:=i
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
End With
End Sub
Sub highlightNegativeNumbers()
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
Exit Sub
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)
Next
End With
Next I
End Sub
Sub highlightCommentCells()
Selection.SpecialCells(xlCellTypeComments).Select
Selection.Style= "Note"
End Sub
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
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
Next rng
MsgBox "There are total " & i &" "& c & " in this worksheet."
End Sub
Sub blankWithSpace()
rng.Style = "Note"
End If
Next rng
End Sub
Sub highlightMaxValue()
rng.Style = "Good"
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
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
Printing Codes
These macro codes will help you to automate some printing tasks which can further
save you a ton of time.
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
ActiveWindow.SelectedSheets.PrintOutCopies:=1, Collate:=True,
IgnorePrintAreas:=False
End Sub
Sub printSelection()
Selection.PrintOutCopies:=1, Collate:=True
End Sub
Let�s say you want to print pages from 5 to 10. You just need to run this VBA code
and enter start page and end page.
Sub printCustomSelection()
Value")
Exit Sub
End If
Value")
Exit Sub
End If
Collate:=True
End Sub
Worksheet Codes
These macro codes will help you to control and manage worksheets in an easy way and
save your a lot of time.
Sub HideWorksheet()
Dim ws As Worksheet
ws.Visible = xlSheetHidden
End If
Next ws
End Sub
35. Unhide all Hidden Worksheets
And if you want to un-hide all the worksheets which you have hide with previous
code, here is the code for that.
Sub UnhideAllWorksheet()
Dim ws As Worksheet
ws.Visible = xlSheetVisible
Next ws
End Sub
When you run this macro it will compare the name of the active worksheet with other
worksheets and then delete them.
Sub DeleteWorksheets()
Dim ws As Worksheet
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
End Sub
When you run this macro, you will get an input box to enter a password. Once you
enter your password, click OK. And make sure to take care about CAPS.
Sub ProtectAllWorskeets()
Dim ws As Worksheet
Dim ps As String
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
When you run this macro code you will get an input box to enter the total number of
sheets you want to enter.
Sub InsertMultipleSheets()
Dim i As Integer
Multiple Sheets")
End Sub
Sub ProtectWS()
End Sub
41. Un-Protect Worksheet
If you want to unprotect your worksheet you can use this macro code.
All you have to do just mention your password which you have used while protecting
your worksheet.
Sub UnprotectWS()
ActiveSheet.Unprotect "mypassword"
End Sub
Sub SortWorksheets()
Dim i As Integer
Dim j As Integer
Worksheets")
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
.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
Sub UnhideRowsColumns()
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
End Sub
Sub SaveWorkshetAsPDF()
Dimws As Worksheet
End Sub
Sub DisablePageBreaks()
Application.ScreenUpdating= False
Next Sht
Next wb
Application.ScreenUpdating= True
End Sub
Workbook Codes
These codes will help you to perform workbook level tasks in an easy way and with
minimum efforts.
It will save a backup file in the same directory where your current file is saved
and it will also add the current date with the name of the file.
Sub FileBackUp()
End Sub
This macro code will first check all the workbooks one by one and close them. If
any of the worksheets is not saved, you'll get a message to save it.
Sub CloseAllWorkbooks()
wbs.Close SaveChanges:=True
Next wb
End Sub
Sub CopyWorksheetToNewWorkbook()
ThisWorkbook.ActiveSheet.Copy _
Before:=Workbooks.Add.Worksheets(1)
End Sub
You can change the subject, email, and body text in code and if you want to send
this mail directly, use ".Send" instead of ".Display".
Sub Send_Mail()
With OutMail
.to = "[email protected]"
.display
End With
End Sub
Sub OpenWorkbookAsAttachment()
Application.Dialogs(xlDialogSendMail).Show
End Sub
file."
End Sub
Sub auto_close()
excelchamps.com"
End Sub
Sub VisibleWorkbooks()
Dim i As Integer
End If
Next book
MsgBox i
End Sub
First of all, make sure to select a cell from your pivot table and then run this
macro.
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
Just run this code and all of your pivot tables in your workbook will be refresh in
a single shot.
Sub CloseAllWorkbooks()
wbs.Close SaveChanges:=True
Next wb
End Sub
Sub UpdatePivotTableRange()
PivotName = "PivotTable2"
Data_Sheet.Activate
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
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
Charts Codes
Use these VBA codes to manage charts in Excel and save your lot of time.
All you have to do just specify to which type you want to convert.
There are different codes for different types, you can find all those types from
here.
Sub ChangeChartType()
ActiveChart.ChartType = xlColumnClustered
End Sub
You just need to select your chart and run this code.
Sub ConvertChartToPicture()
ActiveChart.ChartArea.Copy
ActiveSheet.Range("A1").Select
ActiveSheet.Pictures.Paste.Select
End Sub
Sub AddChartTitle()
Dim i As Variant
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Text = i
Last:
Exit Sub
End Sub
Advanced Codes
Some of the codes which you can use to preform advanced task in your spreadsheets.
First of all, make sure to select a cell from your pivot table and then run this
macro.
Sub HideSubtotals()
Dim pt As PivotTable
Dim pf As PivotField
If pt Is Nothing Then
Exit Sub
End If
pf.Subtotals(1) = True
pf.Subtotals(1) = False
Next pf
End Sub
When you run this code it will create a new worksheet and create a index of
worksheets with a 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
You just have to select the range and once you run this code it will automatically
insert a picture for that range.
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
Excel will speak all the text what you have in that range, cell by cell.
Sub Speak()
Selection.Speak
End Sub
Sub DataForm()
ActiveSheet.ShowDataForm
End Sub
Learn more about goal seek from here before you use this code.
Sub GoalSeekVBA()
Worksheets("Goal_Seek").Activate
.GoalSeek_ Goal:=Target, _
ChangingCell:=Range("C2")
End With
Exit Sub
End Sub
Sub SearchWindow32()
search_string = query
'Uncomment the following line for Windows 64 versions and comment out Windows 32
versions'
chromePath = "C:Program
FilesGoogleChromeApplicationchrome.exe"
'Uncomment the following line for Windows 32 versions and comment out Windows 64
versions
(x86)GoogleChromeApplicationchrome.exe"
End Sub
Formula Codes
These codes will help you to calculate or get results which often you do with
worksheet functions and formulas.
72. Convert all Formulas into Values
Simply convert formulas into values.
When you run this macro it will quickly change the formulas into absolute values.
Sub ConvertToValues()
Select Case MsgBox("You Can't Undo This Action. " & "Save
Case Is = vbYes
ThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
If MyCell.HasFormula Then
MyCell.Formula = MyCell.Value
End If
Next MyCell
End Sub
It will check your selection and then remove all 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
All you need is to refer to a cell or insert a text into the function and number of
characters to remove from the text string.
It has two arguments "rng" for the text string and "cnt" for the count of
characters to remove.
For example: If you want to remove first characters from a cell, you need to enter
1 in cnt.
End Function
Sub degreeSymbol( )
rng.Select
If IsNumeric(ActiveCell.Value) Then
End If
End If
Next
End Sub
rvrse = VBA.strReverse(cell.Value)
End Function
Sub DataForm()
ActiveSheet.ShowDataForm
End Sub
Sub ActivateA1()
Application.ReferenceStyle = xlA1
Else
Application.ReferenceStyle = xlA1
End If
End Sub
Sub TimeStamp()
Dim i As Integer
For i = 1 To 24
ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select
Next i
End Sub
Sub date2day()
Selection.Value = Selection.Value
With tempCell
.Value = Day(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub
Sub date2year()
Selection.Value = Selection.Value
With tempCell
.Value = Year(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub
82. Remove Time from Date
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
Sub removeDate()
End If
End Sub
It will check each and every cell of selected range and then convert it into upper
case text.
Sub convertUpperCase()
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value = UCase(Rng)
End If
Next
End Sub
Just select a range of cells where you have text and run this code.
If a cell has a number or any value other than text that value will remain same.
Sub convertLowerCase()
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value= LCase(Rng)
End If
Next
End Sub
Sub convertProperCase()
If WorksheetFunction.IsText(Rng) Then
Rng.Value= WorksheetFunction.Proper(Rng.Value)
End If
Next
End Sub
Sub convertTextCase()
If WorksheetFunction.IsText(Rng) Then
Rng.Value= UCase(Left(Rng, 1)) & LCase(Right(Rng, Len(Rng) -1))
End If
Next rng
End Sub
It will show you an input box to enter the character you want to remove.
Sub removeChar()
Dim rc As String
Next
End Sub
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
End Sub
Sub removeApostrophes()
Selection.Value = Selection.Value
End Sub
Sub removeDecimals()
rng.Value= Int(rng)
rng.NumberFormat= "0"
Next rng
End Sub
Select that range of cells and run this code. It will first ask you for the number
with whom you want to multiple and then instantly multiply all the numbers with it.
Sub multiplyWithNumber()
"Input Required")
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng * c
Else
End If
Next rng
End Sub
Sub addNumber()
DimiAs Integer
If WorksheetFunction.IsNumber(rng) Then
rng.Value= rng+ i
Else
End If
Next rng
End Sub
It will simply check 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
Next rng
End Sub
It will simply check all 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
Sub addcAlphabets()
Dim i As Integer
For i= 65 To 90
ActiveCell.Value= Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
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
97. Convert Roman Numbers into Arabic Numbers
Sometimes it�s really hard to understand Roman numbers as serial numbers. This code
will help 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
Sub removeNegativeSign()
Selection.Value= Selection.Value
If WorksheetFunction.IsNumber(rng)
End If
Next rng
End Sub
Sub replaceBlankWithZero()
Selection.Value= Selection.Value
rng.Value= "0"
Else
End If
Next rng
End Sub