Excel VB Sample Codes
Excel VB Sample Codes
46 COMMENTS
Macro codes can save you a ton of time. You can automate small as well as heavy tasks with VBA codes.
And, do you know with the help of macros, you can break all the limitations of excel which you think Excel
has?
So, today, I have listed some of the useful codes examples to help you become more productive in your day
to day work.
You can use these codes even if you haven't used VBA before that. All you have to do just paste these codes
These codes will exactly do the same thing which headings are telling you. For your convenience, please
Important: This is my Ultimate Code Vault which I update on monthly basis with new codes. It would be
great if you bookmark this page and keep on visiting to new codes every time.
First of all, make sure you have your developer tab on your Excel ribbon to access VB editor.
If you don't have please use these simple steps to activate developer tab.
On the left side in "Project Window", right click on the name of your workbook and insert a new
module.
Just paste your codes into the module and close it.
It will show you a window with a list of the macros you have in your file. And, you can run a macro
Enter your name and email below to get a Free PDF copy directly into your inbox.
Quick Navigation
Basic
Formatting
Printing
Worksheet
Workbook
Pivot Table
Charts
Advanced
Formulas
1
Basic
These VBA codes will help you to perform some basic tasks in a flash which you frequently do in 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 an input box and you need enter max number. After that, it will insert
Sub AddSerialNumbers()
Dim i As Integer
For i = 1 To iActiveCell.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 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
Once you run this macro it will show an input box and you need to enter the number of rows you want to
insert.
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 cells in your worksheet
Sub AutoFitColumns()
Cells.Select
Cells.EntireColumn.AutoFit
End Sub
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 click.
It will first select all the columns and then remove text wrap and auto fit all the rows and columns.
Sub RemoveWrapText()
Cells.Select
Selection.WrapText = False
Cells.EntireRow.AutoFit
Cells.EntireColumn.AutoFit
End Sub
Unmerge Cells
Select your cells and run this code and it will unmerge all the cells from the selection with your loosing data.
Sub UnmergeCells()
Selection.UnMerge
End Sub
Open Calculator
In window there is a specific calculator and by using this macro code you can open that calculator directly
Application.ActivateMicrosoftApp Index:=0
End Sub
Use this code to add a date into the header or footer in your worksheet. You can edit this code for switching
Sub dateInHeader()
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = "&D"
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
ActiveWindow.View = xlNormalView
End Sub
Custom Header/Footer
If you want to insert a custom header then this code is for you. 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()
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = myText
.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 code will add serial
numbers up to 5000 in your sheet and along with it will show progress on the 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
Formatting
These VBA codes will help you to format cells and ranges using some specific criteria and conditions.
This macro will check each cell of your selection and highlight the duplicate values. You can also change the
Sub HighlightDuplicateValues()
End If
Next myCell
End Sub
I really love this macro code whenever I have to analyze a data table. Here are the quick steps to apply this
code.
2. Go to Project Explorer (Ctrl + R, If hidden). Select your workbook & double click on the 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 menu.
Remember that, by applying this macro you will not able to edit the cell by double click.
Target.Cells.EntireRow.Address
Range(strRange).Select
End Sub
Just select a range and run this macro and it will highlight top 10 values with the green color.
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
Selection.FormatConditions(1).StopIfTrue = False
End Sub
If you are not sure about how many named ranges you have in your worksheet then you can use this code
Sub HighlightRanges()
Dim RangeName As Name
HighlightRange.Interior.ColorIndex = 36
Next RangeName
End Sub
Once you run this code it will ask you for the value from which you want to highlight all greater values.
Sub HighlightGreaterThanValues()
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
Once you run this code it will ask you for the value from which you want to highlight all lower values.
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
Select a range of cells and run this code. It will check each cell from the range and highlight all cells the
Sub highlightNegativeNumbers()
If WorksheetFunction.IsNumber(Rng) Then
Rng.Font.Color= -16776961
End If
End If
Next
End Sub
Suppose you have a large dataset and you want to check for a particular value. For this, you can use this
code. When you run it, you will get an input box to enter the value to search for.
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
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
Sub highlightAlternateRows()
If rng.RowMod 2 = 1 Then
rng.Value= rng^ (1 / 3)
Else
End If
Next rng
End Sub
If you find hard to check all the cells for spelling error then this code is for you. It will check each cell from
Sub HighlightMisspelledCells()
Next rng
End Sub
it will return a message with the number error cells and highlight all the cells.
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
This code will help you to count the cells which have a specific value which you will mention and after that
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
Highlight all the Cells in a Worksheet which are Blank but have an Invisible Space
Sometimes there are some cells which are blank but they have a single space. And, due to this, it’s really
hard to identify them. This code will check all the cell in the worksheet and highlight all the cells which have
a single space.
Sub blankWithSpace()
rng.Style = "Note"
End If
Next rng
End Sub
It will check all the selected cells and highlight the cell with the maximum value.
Sub highlightMaxValue()
rng.Style = "Good"
End If
Next rng
End Sub
It will check all the selected cells and highlight the cell with the Minimum value.
Sub highlightMinValue()
rng.Style = "Good"
End If
Next rng
End Sub
This codes will highlight all the cells from the selection which has a unique value.
Sub highlightUniqueValues()
rng.FormatConditions.Delete
Dim uv As UniqueValues
Set uv = rng.FormatConditions.AddUniqueValues
uv.DupeUnique = xlUnique
uv.Interior.Color = vbGreen
End Sub
Using this code you can highlight the difference between two columns (corresponding cells).
Sub columnDifference()
Range("H7:H8,I7:I8").Select
Selection.ColumnDifferences(ActiveCell).Select
Selection.Style= "Bad"
End Sub
And, by using this code you can highlight difference between two row (corresponding cells).
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 further save you a ton of time.
Print Comments
Use this macro to activate settings to print cell comments in the end of the page. Let’s say you have 10
pages to print, after using this code you will get all the comments on 11th last page.
Sub printComments()
With ActiveSheet.PageSetup
.printComments= xlPrintSheetEnd
End With
End Sub
Use this VBA code to take a print with a narrow margin. When you run this macro it will automatically
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
This code will help you print selected range. You don't need to go to printing options and set printing range.
Sub printSelection()
Selection.PrintOutCopies:=1, Collate:=True
End Sub
Instead of using the setting from print options you can use this code to print custom page range. 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()
Exit Sub
End If
Exit Sub
End If
Selection.PrintOutFrom:=startpage, To:=endpage, Copies:=1, Collate:=True
End Sub
4
Worksheet
These macro codes will help you to control and manage worksheets in an easy way and save your a lot of
time.
Now, let's say if you want to hide all the worksheets in your workbook other than the active worksheet. This
Sub HideWorksheet()
Dim ws As Worksheet
ws.Visible = xlSheetHidden
End If
Next ws
End Sub
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
If you want to delete all the worksheets other than the active sheet, this macro is useful for you. 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
If you want to protect your all worksheets in one go here is a code for you. 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
Dim ws As Worksheet
Dim ps As String
ws.Protect Password:=ps
Next ws
End Sub
Make all chart same in size. This macro code will help you to make all the charts of the same size. You can
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
You can use this code if you want to add multiple worksheets in your workbook in a single shot. 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
End Sub
Protect Worksheet
If you want to protect your worksheet you can use this macro code. All you have to do just mention your
Sub ProtectWS()
End Sub
Unprotect Worksheet
If you want to unprotect your worksheet you can use this macro code. All you have to do just mention your
Sub UnprotectWS()
ActiveSheet.Unprotect "mypassword"
End Sub
Sort Worksheets
This code will help you to sort worksheets in your workbook according to their name.
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
To protect cell with formula with a single click you can use this code.
Sub lockCellsWithFormulas()
With ActiveSheet
.Unprotect
.Cells.Locked = False
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Protect AllowDeletingRows:=True
End With
End Sub
Run this code and it will check all the worksheets in the active workbook. And, delete if a worksheet is
blank.
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
Unhide all Rows And Columns
Instead of unhiding rows and columns on by one manually you can use this code to do this in a single go.
Sub UnhideRowsColumns()
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
End Sub
This code will simply save all the worksheets in a separate PDF file. You just need to change the folder name
Sub SaveWorkshetAsPDF()
Dimws As Worksheet
For Each ws In Worksheetsws.ExportAsFixedFormat xlTypePDF, “ENTER-FOLDER-NAME-HERE" & ws.Name & ".pdf" Nextws
End Sub
To disable page breaks use this code. It will simply disable page breaks from all the open workbooks.
Sub DisablePageBreaks()
Application.ScreenUpdating= False
Next wb
Application.ScreenUpdating= True
End Sub
5
Workbook
These codes will help you to perform workbook level tasks in an easy way and with minimum efforts.
This is one of the most useful macros which can help you to save a backup file of your current workbook. It
will save a backup file in the same directory where your current file is saved. And, it will also add the current
Sub FileBackUp()
ThisWorkbook.name
End Sub
Use this macro code to close all open workbooks. 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
Let's say if you want to copy your active worksheet in a new workbook, just run this macro code and it will
Sub CopyWorksheetToNewWorkbook()
ThisWorkbook.ActiveSheet.Copy _
Before:=Workbooks.Add.Worksheets(1)
End Sub
Use this macro code to quickly send your active workbook in an e-mail. 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 = "Sales@FrontLinePaper.com"
.Attachments.Add ActiveWorkbook.FullName
.display
End With
End Sub
Once you run this macro it will open your default mail client and attached active workbook with it as an
attachment.
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 name your macro
"auto_open".
Sub auto_open()
End Sub
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()
MsgBox "Bye Bye! Don't forget to check other cool stuff on excelchamps.com"
End Sub
Let’s you have 5-10 open workbooks, you can use this code to get the number of workbooks which are not
saved yet.
Sub VisibleWorkbooks()
Dim i As Integer
i = i + 1
End If
Next book
MsgBox i
End Sub
6
Pivot Table
These codes will help you to manage and make some changes in pivot tables in a flash.
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
A super quick method to refresh all pivot tables. Just run this code and all of your pivot tables in your
Sub RefreshAllPivotTables()
Dim ws As Worksheet
Dim pt As PivotTable
pt.RefreshTable
Next pt
Next ws
End Sub
Follow this step by step guide to create a pivot table using VBA.
If you are not using Excel tables then you can use this code to update pivot table range.
Sub UpdatePivotTableRange()
PivotName = "PivotTable2"
'Defining Staring Point & Dynamic Range
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
To disable/enable GetPivotData function you need to use Excel option. But, with this code you can do it in a
single click.
Sub activateGetPivotData()
Application.GenerateGetPivotData = True
End Sub
Sub deactivateGetPivotData()
Application.GenerateGetPivotData = False
End Sub
7
Charts
Use these VBA codes to manage charts in Excel and save your lot of time.
This code will help you to convert chart type without using chart options from the tab. All you have to do
Below code will convert selected chart to a clustered column chart. There are different codes for different
Sub ChangeChartType()
ActiveChart.ChartType = xlColumnClustered
End Sub
This code will help you to convert your chart into an image. 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
First of all, you need to select your chart and the run this code. You will get an input box to enter chart title.
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 spreadsheets.
Select a range, run this macro and you will get a PDF file for that selected range. It's really cool.
Sub SaveAsPDF()
End Sub
Create a Table of Content
Let's say you have more than 100 worksheets in your workbook. And, it's hard to navigate now.Don't worry
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
Paste selected range as an image. You just have to select the range and once you run this code it will
Sub PasteAsPicture()
Application.CutCopyMode = False
Selection.Copy
ActiveSheet.Pictures.Paste.Select
End Sub
This VBA code will convert your selected range into a linked picture and you can use that image anywhere
you want.
Sub LinkedPicture()
Selection.Copy
ActiveSheet.Pictures.Paste(Link:=True).Select
End Sub
Just select a range and run this code, excel will speak all the text what you have in that range, cell by cell.
Sub Speak()
Selection.Speak
End Sub
Activate Data Entry Form
There is a default data entry form in Excel which you can use for data entry. And, you can use this code to
Sub DataForm()
ActiveSheet.ShowDataForm
End Sub
Goal Seek can be super helpful for you to solve complex problems. Learn more about goal seek from here
Sub GoalSeekVBA()
.GoalSeek_ Goal:=Target, _
ChangingCell:=Range("C2")
End With
Exit Sub
End Sub
Follow this post get the VBA code to search on google directly from Excel.
9
Formulas
These codes will help you to calculate or get results which often you do with worksheet functions and
formulas.
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 Workbook First?", vbYesNoCancel, "Alert")
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
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 a cell or insert a text
into the function and number of characters to remove from the text string.
t 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 incnt.
Public Function removeFirstC(rng As String, cnt As Long)
End Function
Let’s say you have a list of numbers in a column and you want to add degree symbol with all of 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 have text which you
want to reverse.
rvrse = VBA.strReverse(cell.Value)
End Function
Activate R1C1 Reference Style
This macro code will help you to activate R1C1 reference style without using Excel options.
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 options.
Sub ActivateA1()
Application.ReferenceStyle = xlA1
Else
Application.ReferenceStyle = xlA1
End If
End Sub
Insert Timestamp
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 then this 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
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
Remove Date from Date and Time
Sub removeDate()
End If
End Sub
Select the cells and run this code. It will check each and every cell of selected range and then convert it into
Sub convertUpperCase()
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value = UCase(Rng)
End If
Next
End Sub
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
And, this code will convert selected text into the proper case where you have the first letter in capital and
rest in small.
Sub convertProperCase()
If WorksheetFunction.IsText(Rng) Then
Rng.Value= WorksheetFunction.Proper(Rng.Value)
End If
Next
End Sub
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 you an input box to
Sub removeChar()
Dim rc As String
Next
End Sub
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 this code 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 selected range.
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 particular. Just use this
code.
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()
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng * c
Else
End If
Next rng
End Sub
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 simply check all the
Sub getSquareRoot()
Dim i As Integer
If WorksheetFunction.IsNumber(rng) Then
rng.Value= Sqr(rng)
Else
End If
Next rng
End Sub
To calculate cube root without applying a formula you can use this code. It will simply check all the selected
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 code 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
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 will help you to
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 numbers into positive.
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 easier to use formula and
Sub replaceBlankWithZero()
Selection.Value= Selection.Value
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 also help you in your
work.
But, you have to help me to update this list. If you have any useful code which you use in work to save your
time, please share with me in the comment section, I’d love to hear from you.
And, please don’t forget to share this list with your friends.
Share
Tweet
Enter your name and email below to get a Free PDF copy directly into your inbox.
DOWNLOAD NOW
EXCEL PRODUCTIVITY GUIDE
With this guide, you can take your skills to whole next level. It will help you to win at your daily work using some smart tactics.
30 Useful Excel Tips
80 Excel Keyboard Shortcuts
“Your excel book is immensely helpful. Thank you for sharing it”