Professional Documents
Culture Documents
Ready to Use 101 Excel Powerful Microsoft Excel VBA Code is an independent
publication and is not affiliated with, nor has it been authorized, sponsored, or otherwise
approved by Microsoft Corporation.
Trademarks
Microsoft, Visual Basic, Excel and Windows are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries.
Liability
The purpose of this book is to provide basic guideline for people interested in Excel VBA
programming. Collection of ready code has been used on reality platform by technical and
non-technical users on their routine. Although every effort and care has been taken to make
the information as accurate as possible, the author shall not be liable for any error, harm or
damage arising from using the instructions given in this book.
ISBN: 9781973519478
All rights reserved. No part of this book may be reproduced or transmitted in any form or by
any means, without permission in writing from the author.
Acknowledgement
I would like to express my sincere gratitude to many people and Excel Learning Websites who
have made their contributions in one way or another to the successful publication of this book.
My special thanks go to my Parents and Gurudev (Acharya Sh Ramesh) and friend Mr. Rakesh
Jain (Charvi Associates) having expert knowledge of web programming & My Accounts, HR, IT
& ERP Departments Colleague contributed their ideas and even wrote some of the sample
programs for this book. I would also like to appreciate the support provided by my beloved
wife Manisha Jain, son Master Samkit and youngest daughter Samiksha Jain and Friends.
I would also like to thank the million of visitors to my Smart Excel & Learning website at
http://www.anilnahar.com l for their support and encouragement.
Anil Nahar holds a Master degree in Computer Application (MCA), a Bachelor degree in
Commerce (B.Com.) and Three year completed C.A. training by ICAI ( Institute of Chartered
Accountant of India). He is working on real platform with a esteem organization on Functional
as well as Technical Support in Excel. He is provided many smart excel training programmes
in corporate and appreciated by management. He has been involved in programming for more
than 10 years. He created the popular online Smart Learning Tricks Tutorial at
www.anilnahar.com in 2017 and since then the web site has attracted millions of visitors and it
is one of the top searched VBA Excel websites in many search engines including Google.
Table of Contents
How to Insert VBA code to Excel Workbook
How to run VBA macros in Excel
Adding Or Subtract By Specific Value To All
Alphabets Serial Capital And Small Letter
Auto Fit Columns
Auto Fit Rows
Auto Save And Close Workbook
Automatically Invoice Number Generator
Blank Cell Fill With Zero Value
Calculator Open
Change Multiple Field Settings In Pivot Table
Chart Heading Mark
Combine Duplicate Rows And Sum The Values
Convert Columns And Rows Into Single Column
Convert Month Name To Number
Convert Negative To Positive Value
Convert Number To Month Name
Convert One Cell To Multiple Rows
Convert Text To Column
Count Number Of Words In Selected Range
Count Total Words In Worksheet
Create A Monthly Calendar
Create Folders Based On Cell Values By Selection Range
Cube Root To All
Data Entry Form Of Activate Sheet
Delete All Blank Worksheets
Delete All Worksheets
Delete Apostrophe In Text Or Number
Delete Decimal Value
Delete Every Other Row In Selection
Delete Input Value In Range
Fill Blank Cells With 0 Or Other Specific Value
Find Duplicates Value From Two Columns
Hide All Inactive Worksheets
Highilght Specific Text
Highlight Alternate Rows With Color
Highlight Color Maximum Ten And Other Number
Highlight Color Of Duplicate Value
Highlight Greater Than Value By Input
Highlight Highest Value
Highlight Lowest Value
Highlight Mispelled Cell Text
Highlight Name Range Values
Highlight Negative Number
Highlight Text With Color Based On Second Column
Highlight Unique Value
Image Conversion Of Selection Area
Image Creation Of Chart
Image Linked Of Selction Area
Import All Files Path And Summary Of Folder And Sub Folder
Import Multiple Text Files
Index Worksheets With Hyperlink
Indexing All Worksheet Name In Of Active Workbook
Indexing Name Of Files In Windows Folder
Insert Worksheets
Insert Columns
Insert Header And Footer By Input Text
Insert Header And Footer Current Date
Insert Rows
Inserting All Worksheets Names In Cells
Lock Formula Cell
Lower Case All
Merge All Worksheets Of Active Workbook Into One Worksheet
Multiply By Specific Value To All
Password Breaker Workbook
Password Breaker Worksheet
Password Protect Without Unprotecting Worksheet
Password Protected Workbook
Password Unprotected Workbook
Pivot Table Update Auto
Print And Print Preview To Area By Input
Print Comments In Last Page
Print Multiple Selection Range Only
Proper Case All
Protect And Unprotect Worksheets
Protect To Other Insert Worksheet
Remove Blank Rows Of The Selected Range
Remove Entire Rows Based On Cell Value
Remove Leading Spaces
Remove Wrap Text
Rename All Sheets By Entering A Specific Name
Rename Worksheets By A Specific Cell Value
Repeat Cell Values X Times
Save As Worksheet To Workbook
Select All Bold Cells In A Range
Select Entire Column Except Header
Sentance Case Conversion
Sort Sheets In Alphabetical
Sort Worksheet Tabs By Color
Sorting All Worksheets By Ascending Or Descending
Split A Workbook Into Multiple Workbooks And Save In The Same
Folder
Split Cells Into Multiple Rows Based On Carriage Returns
Split Data Into Multiple Worksheets Based On Column
Split Data Into Multiple Worksheets By Rows Count
Split Word Or Number Into Separate Cells
Square Root To All
Status Bar Progress
Swap Two Nonadjacent Cell Contents
Unhide All Hidden Worksheets
Unhide All Rows And Columns
Unmerge Cells
Upper Case All
Wrap Text Of Selection Range
How to Insert VBA code to Excel Workbook
This is a brief step-by-step guideline for beginners showing how to add VBA code (Visual Basic
for Applications code) to your Excel workbook and run this macro to solve your spreadsheet
tasks.
This step-by-step guide to be able to use the code you found in this E-Book :
1. Open your workbook in Excel.
2. Press Alt+F11 to open Visual Basic Editor (VBE).
3. Click on your workbook name in the "Project-VBAProject" pane (at the top left
corner of the editor window) and select Insert -> Module from the context
menu.
4. Copy the VBA code and paste it to the right pane of the VBA editor ("Module1"
window).
5. Then add the following lines to get your macro to work faster.
To the very beginning of the code, after all code lines that start with Dim (if there are no
"Dim" lines, then add them right after the Sub line):
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
These lines, as their names suggest, turn off screen refresh and recalculating the workbook's
formulas before running the macro.
After the code is executed, everything is turned back on. As a result, the performance is
increased from 10% to 500% (aha, the macro works 5 times faster if it continuously
manipulates the cells' contents).
Save your workbook as "Excel macro-enabled workbook". Press Ctrl+S, then click the "No"
button in the "The following features cannot be saved in macro-free workbook" warning
dialog.
The "Save as" dialog will open. Choose "Excel macro-enabled workbook" from the "Save as
type" drop-down list and click the Save button.
Press Alt+Q to close the Editor window and switch back to your workbook.
How to run VBA macros in Excel
When you want to run the VBA code that you added as described in the section above: press
Alt+F8 to open the "Macro" dialog.
Then select the wanted macro from the "Macro Name" list and click the "Run" button.
Adding Or Subtract By Specific Value To All
Sub add_substract_all()
' Smart code for Adding/Substract Number by Input to all selection range value
Dim i As Integer
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng + i
Else
End If
Next rng
End Sub
Alphabets Serial Capital And Small Letter
Sub Alphabets_capital()
' Smart code for Serial Alphabets in Capital Letters from select cell
Dim i As Integer
For i = 65 To 90
ActiveCell.Value = Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
End Sub
---------------
Sub Alphabets_small()
' Smart code for Serial Alphabates in Small Letters from select cell
Dim i As Integer
For i = 97 To 122
ActiveCell.Value = Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
End Sub
Auto Fit Columns
Sub AutoFitColumns()
Cells.Select
Cells.EntireColumn.AutoFit
End Sub
Auto Fit Rows
Sub AutoFitRows()
Cells.Select
Cells.EntireRow.AutoFit
End Sub
Auto Save And Close Workbook
Sub AutoSave()
' Smart code for Auto Save and quit workbook a certain time
Application.DisplayAlerts = False
ActiveWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
End Sub
Automatically Invoice Number Generator
Range("D2").Value = Range("D2").Value + 1
End Sub
Blank Cell Fill With Zero Value
Sub Zero_blankcell()
' Smart code for fill zero value in blank cell in selection range
Selection.Value = Selection.Value
rng.Value = "0"
Else
End If
Next rng
End Sub
Calculator Open
Sub OpenCalculator()
Application.ActivateMicrosoftApp Index:=0
End Sub
Change Multiple Field Settings In Pivot Table
With WorkRng.PivotTable
.ManualUpdate = True
With xPF
.Function = xlSum
.NumberFormat = "#,##0"
End With
Next
.ManualUpdate = False
End With
End Sub
Chart Heading Mark
Sub ChartHeading()
' Smart code for Add Chart Heading of Selected Chart by Input Value
Dim i As Variant
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Text = i
Last:
Exit Sub
End Sub
Combine Duplicate Rows And Sum The Values
Sub CombineRows()
xTitleId = "SmartExcel(anilnahar.com)"
arr = WorkRng.Value
For i = 1 To UBound(arr, 1)
Next
Application.ScreenUpdating = False
WorkRng.ClearContents
WorkRng.Range("A1").Resize(Dic.Count, 1) =
Application.WorksheetFunction.Transpose(Dic.keys)
WorkRng.Range("B1").Resize(Dic.Count, 1) =
Application.WorksheetFunction.Transpose(Dic.items)
Application.ScreenUpdating = True
End Sub
Convert Columns And Rows Into Single Column
Sub ConvertRangeToColumn()
xTitleId = "SmartExcel(anilnahar.com)"
rowIndex = 0
Application.ScreenUpdating = False
Rng.Copy
Next
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Convert Month Name To Number
Sub ChangeNum()
xTitleId = "SmartExcel(anilnahar.com)"
End If
Next
End Sub
Convert Negative To Positive Value
Sub convert_positive()
Selection.Value = Selection.Value
If WorksheetFunction.IsNumber(rng) Then
rng.Value = Abs(rng)
End If
Convert Number To Month Name
Sub ChangeMonth()
xTitleId = "SmartExcel(anilnahar.com)"
Next
End Sub
Convert One Cell To Multiple Rows
Sub TransposeRange()
xTitleId = "SmartExcel(www.anilnahar.com)"
End Sub
Convert Text To Column
Sub Text_to_Column()
one_to_how_many_columns = 10
Application.DisplayAlerts = False
Next col_count
If Application.WorksheetFunction.CountIf(selected_range_individual_column(col_count), "
<>") = 0 Then GoTo next_loop:
selected_range_individual_column(col_count).TextToColumns _
Destination:=selected_range.Cells(selected_range.Row, one_to_how_many_columns *
col_count + 1), _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=True, _
Tab:=False, _
Semicolon:=False, _
Comma:=False, _
Space:=True, _
Other:=False, _
FieldInfo:=Array( _
Array(0, 1), _
Array(3, 1), _
Array(6, 1), _
Array(12, 1), _
Array(17, 1) _
), _
TrailingMinusNumbers:=True
next_loop:
Next col_count
err_occured:
Application.DisplayAlerts = True
End Sub
Count Number Of Words In Selected Range
Sub CountWords()
xAddress = ActiveWindow.RangeSelection.Address
Application.ScreenUpdating = False
Exit Sub
End If
xRgVal = xRgEach.Value
xRgVal = Application.WorksheetFunction.Trim(xRgVal)
End If
Next xRgEach
MsgBox "Words In Selection Is: " & Format(xRgNum, "#,##0"), vbOKOnly, "Smart Excel
(www.anilnahar.com)"
Application.ScreenUpdating = True
End Sub
Count Total Words In Worksheet
Sub CountWordWS()
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 this worksheet"
End Sub
Create A Monthly Calendar
Sub CalendarMaker()
Scenarios:=False
Application.ScreenUpdating = False
Range("a1:g14").Clear
MyInput = InputBox("Type in Month and year for Calendar in format mm/yy ")
StartDay = DateValue(MyInput)
Year(StartDay))
End If
With Range("a1:g1")
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
.Font.Size = 18
.Font.Bold = True
.RowHeight = 35
End With
With Range("a2:g2")
.ColumnWidth = 11
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.Orientation = xlHorizontal
.Font.Size = 12
.Font.Bold = True
.RowHeight = 20
End With
Range("a2") = "Sunday"
Range("b2") = "Monday"
Range("c2") = "Tuesday"
Range("d2") = "Wednesday"
Range("e2") = "Thursday"
Range("f2") = "Friday"
Range("g2") = "Saturday"
With Range("a3:g8")
.HorizontalAlignment = xlRight
.VerticalAlignment = xlTop
.Font.Size = 18
.Font.Bold = True
.RowHeight = 21
End With
'Format MM/YY
DayofWeek = Weekday(StartDay)
CurYear = Year(StartDay)
CurMonth = Month(StartDay)
Case 1
Range("a3").Value = 1
Case 2
Range("b3").Value = 1
Case 3
Range("c3").Value = 1
Case 4
Range("d3").Value = 1
Case 5
Range("e3").Value = 1
Case 6
Range("f3").Value = 1
Case 7
Range("g3").Value = 1
End Select
RowCell = cell.Row
ColCell = cell.Column
cell.Value = ""
Exit For
End If
End If
cell.Value = ""
Exit For
End If
End If
Next
For x = 0 To 5
Range("A4").Offset(x * 2, 0).EntireRow.Insert
With Range("A4:G4").Offset(x * 2, 0)
.RowHeight = 65
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlTop
.WrapText = True
.Font.Size = 10
.Font.Bold = False
.Locked = False
End With
7).Borders(xlLeft)
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
7).Borders(xlRight)
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
Weight:=xlThick, ColorIndex:=xlAutomatic
Next
.Resize(2, 8).EntireRow.Delete
ActiveWindow.DisplayGridlines = False
Scenarios:=True
ActiveWindow.WindowState = xlMaximized
ActiveWindow.ScrollRow = 1
Application.ScreenUpdating = True
Exit Sub
MyErrorTrap:
MsgBox "You may not have entered your Month and Year correctly." _
Resume
End Sub
Create Folders Based On Cell Values By Selection Range
‘ All the selected cells have been created to folders with their values and the folders are
placed into the path as same as the active workbook
Sub MakeFolders()
maxRows = Rng.Rows.Count
maxCols = Rng.Columns.Count
For c = 1 To maxCols
r = 1
End If
r = r + 1
Loop
Next c
End Sub
Cube Root To All
Sub CubeRoot()
Dim i As Integer
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng ^ (1 / 3)
Else
End If
Next rng
End Sub
Data Entry Form Of Activate Sheet
Sub DataForm()
ActiveSheet.ShowDataForm
End Sub
Delete All Blank Worksheets
Sub deleteallblanksheets()
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
Delete All Worksheets
Sub DeleteWorksheets()
Dim ws As Worksheet
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
End Sub
Delete Apostrophe In Text Or Number
Sub delApostrophes()
' Smart code for Delete Apostrophe in any text or Number in selecion range
Selection.Value = Selection.Value
End Sub
Delete Decimal Value
Sub delDecimals()
rng.Value = Int(rng)
rng.NumberFormat = "0"
Next rng
End Sub
Delete Every Other Row In Selection
Sub DeleteEveryOtherRow()
xTitleId = "SmartExcel(anilnahar.com)"
Application.ScreenUpdating = False
rng.EntireRow.Delete
Next
Application.ScreenUpdating = True
End Sub
Delete Input Value In Range
Sub delvalue()
Dim rc As String
Next
End Sub
Fill Blank Cells With 0 Or Other Specific Value
Sub FillEmptyBlankCellWithValue()
If IsEmpty(cell) Then
cell.Value = InputValue
End If
Next
End Sub
Find Duplicates Value From Two Columns
Sub Compare()
Dim Range1 As Range, Range2 As Range, Rng1 As Range, Rng2 As Range, outRng As Range
Application.ScreenUpdating = False
xValue = Rng1.Value
Else
End If
End If
Next
Next
outRng.Select
Application.ScreenUpdating = True
End Sub
Hide All Inactive Worksheets
Sub HideWorksheets()
Dim ws As Worksheet
ws.Visible = xlSheetHidden
End If
Next ws
End Sub
Highilght Specific Text
Sub Highlightspecifictext()
'Smart code for highlight specific text by input in selection range
' SmartExcel(anilnahar.com)
Application.ScreenUpdating = False
Dim Rng As Range
Dim cFnd As String
Dim xTmp As String
Dim x As Long
Dim m As Long
Dim y As Long
cFnd = InputBox("Enter the text value to highlight")
y = Len(cFnd)
For Each Rng In Selection
With Rng
m = UBound(Split(Rng.Value, cFnd))
If m > 0 Then
xTmp = ""
For x = 0 To m - 1
xTmp = xTmp & Split(Rng.Value, cFnd)(x)
.Characters(Start:=Len(xTmp) + 1, Length:=y).Font.ColorIndex = 3
xTmp = xTmp & cFnd
Next
End If
End With
Next Rng
Application.ScreenUpdating = True
End Sub
Highlight Alternate Rows With Color
Sub ColorAlternaterow()
Application.ScreenUpdating = False
For i = 2 To LR Step 2
Rows(i).EntireRow.Interior.ColorIndex = 6
Next i
Application.ScreenUpdating = True
End Sub
Highlight Color Maximum Ten And Other Number
Sub MaxTen()
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
Highlight Color Of Duplicate Value
Sub HighlightDuplicate()
' Smart code for highlight by color of duplicate value in selection range
myCell.Interior.ColorIndex = 44
End If
Next myCell
End Sub
Highlight Greater Than Value By Input
Sub HighlightDuplicate()
' Smart code for highlight by color of duplicate value in selection range
myCell.Interior.ColorIndex = 44
End If
Next myCell
End Sub
Highlight Highest Value
Sub Maxvalue()
rng.Style = "Good"
End If
Next rng
End Sub
Highlight Lowest Value
Sub MinValue()
rng.Style = "Good"
End If
Next rng
End Sub
Highlight Mispelled Cell Text
Sub HighlightMispelledCells()
cl.Interior.ColorIndex = 28
Next cl
End Sub
Highlight Name Range Values
Sub HighlightNameRanges()
' Smart code for highlight colors to name range define values for area
HighlightNameRange.Interior.ColorIndex = 36
Next RangeName
End Sub
Highlight Negative Number
Sub highlightNegativeNumbers()
' Smart code for highlight colors of negative number in selection range
If WorksheetFunction.IsNumber(Rng) Then
Rng.Font.Color = 1677
End If
Highlight Text With Color Based On Second Column
Sub highlightparttext()
'Smart code for Highlight First column text within a cell based on Second column text
Dim I As Long
Dim J As Long
xTxt = ActiveWindow.RangeSelection.AddressLocal
Else
xTxt = ActiveSheet.UsedRange.AddressLocal
End If
LInput:
GoTo LInput
End If
MsgBox "the selected range can only contain two columns "
GoTo LInput
End If
For I = 0 To xRg.Rows.Count - 1
With xRg.Range("A1").Offset(I, 0)
.Font.ColorIndex = 1
For J = 1 To Len(.Text)
Next
End With
Next I
End Sub
Highlight Unique Value
Sub ColorUnique()
rng.FormatConditions.Delete
Dim uv As UniqueValues
Set uv = rng.FormatConditions.AddUniqueValues
uv.DupeUnique = xlUnique
uv.Interior.Color = vbGreen
End Sub
Image Conversion Of Selection Area
Sub Imagework()
' Smart code for Create Image of Selection Area
' Smart Excel(anilnahar.com)
Application.CutCopyMode = False
Selection.Copy
ActiveSheet.Pictures.Paste.Select
End Sub
Image Creation Of Chart
Sub ChartToImage()
ActiveChart.ChartArea.Copy
ActiveSheet.Range("A1").Select
ActiveSheet.Pictures.Paste.Select
End Sub
Image Linked Of Selction Area
Sub LinkedImage()
Selection.Copy
ActiveSheet.Pictures.Paste(Link:=True).Select
End Sub
Import All Files Path And Summary Of Folder And Sub Folder
Sub List_of_folder()
xDir = folder.SelectedItems(1)
End Sub
rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1
rowIndex = rowIndex + 1
Next xFile
If xIsSubfolders Then
Next xSubFolder
End If
End Sub
End If
GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
Else
GetFileOwner = ""
End If
End Function
Import Multiple Text Files
Sub MulipleTextFiles()
'SmartExcel(www.anilnahar.com)
Dim I As Integer
xScreen = Application.ScreenUpdating
Application.ScreenUpdating = False
xDelimiter = "|"
GoTo ExitHandler
End If
I = 1
xTempWb.Sheets(1).Copy
xTempWb.Close False
xWb.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
With xWb
xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=xDelimiter
End With
Loop
ExitHandler:
Application.ScreenUpdating = xScreen
Exit Sub
ErrHandler:
Resume ExitHandler
End Sub
Index Worksheets With Hyperlink
Sub IndexingWs()
' Smart code for Create Index all worksheet with Hyperlink
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
Indexing All Worksheet Name In Of Active Workbook
Sub CreateTOC()
' Smart code for Create Index all worksheet with summary
Dim ws As Worksheet
Dim vbCodeMod
'Summary of ActiveWorkbook
MsgBox "You must have a workbook open first!", vbInformation, "No Open Book"
Exit Sub
End If
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
End With
'If the Table of Contents exists (using a marker range name "TOC_Index") prompt the user
whether to proceed
lngProceed = MsgBox("Index exists!" & vbCrLf & "Do you want to overwrite it?", vbYesNo +
vbCritical, "Warning")
If lngProceed = vbYes Then
Exit Sub
Else
ActiveWorkbook.Sheets(Range("TOC_Index").Parent.Name).Delete
End If
End If
Set ws = ActiveWorkbook.Sheets.Add
ws.Move before:=Sheets(1)
ws.Name = "TOC_Index"
On Error GoTo 0
Else
bNonWkSht = True
End If
Next lngSht
With ws
With .[a1:a4]
.Font.Size = 14
.Cells(1).Font.Bold = True
End With
With .[a6].Resize(lngSht - 1, 1)
.Font.Bold = True
.Font.ColorIndex = 41
.Columns("A:B").EntireColumn.AutoFit
End With
End With
'Add warnings and macro code if there are non WorkSheet types present
If bNonWkSht Then
With ws.[A5]
.Value = "This workbook contains at least one Chart or Dialog Sheet. These sheets will only be
activated if macros are enabled (NB: Please doubleclick yellow sheet names to select them)"
.Font.ColorIndex = 3
.Font.Italic = True
End With
& " Set rng1 = Intersect(Target, Range([a6], Cells(Rows.Count, 1).End(xlUp)))" & vbCrLf _
& " If Err.Number <> 0 Then MsgBox ""Could not select sheet"" & Target.Value" & vbCrLf _
vbCodeMod.CodeModule.AddFromString strWScode
End If
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
End With
ErrHandler:
If Err.Number <> 0 Then MsgBox Err.Description & vbCrLf & "Please note that your
Application settings have been reset", vbCritical, "Code Error!"
End Sub
Indexing Name Of Files In Windows Folder
Option Explicit
Sub GetFileNames()
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = InitialFoldr$
.Show
xFname$ = Dir(xDirect$, 7)
ActiveCell.Offset(xRow) = xFname$
xRow = xRow + 1
xFname$ = Dir
Loop
End If
End With
End Sub
Insert Worksheets
Sub InsertSheets()
Dim i As Integer
End Sub
Insert Columns
Sub InsertColumns()
' Smart code for Insert columns by input no of columns require from select cell
Dim i As Integer
Dim c As Integer
ActiveCell.EntireColumn.Select
For c = 1 To i
Next c
End Sub
Insert Header And Footer By Input Text
Sub InputHeader()
' Smart code for insert text in center of header by input value
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = Text
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
End Sub
Insert Header And Footer Current Date
Sub InputHeader()
' Smart code for insert text in center of header by input value
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = Text
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
End Sub
Insert Rows
Sub InsertRows()
' Smart code for Insert Rows by input no of rows require from select cell
' Smart Excel(anilnahar.com)
Dim i As Integer
Dim r As Integer
ActiveCell.EntireRow.Select
On Error GoTo Last
i = InputBox("Enter number of rows to insert", "Insert Rows")
For r = 1 To i
Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove
Next r
Last: Exit Sub
End Sub
Inserting All Worksheets Names In Cells
Sub SheetNames()
Columns(1).Insert
For i = 1 To Sheets.Count
Cells(i, 1) = Sheets(i).Name
Next i
End Sub
Lock Formula Cell
Sub lockformula()
' Smart code for lock formula cell only in active worksheet
With ActiveSheet
.Unprotect
.Cells.Locked = False
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Protect AllowDeletingRows:=True
End With
Lower Case All
Sub LowerCase()
' Smart code for Convert all in Lower Case by selection range
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value = LCase(Rng)
End If
Next
End Sub
Merge All Worksheets Of Active Workbook Into One Worksheet
Sub Combine()
Dim J As Integer
Sheets(1).Select
Worksheets.Add
Sheets(1).Name = "Combined"
Sheets(2).Activate
Range("A1").EntireRow.Select
Selection.Copy Destination:=Sheets(1).Range("A1")
For J = 2 To Sheets.Count
Sheets(J).Activate
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Copy Destination:=Sheets(1).Range("A65536").End(xlUp)(2)
Next
End Sub
Multiply By Specific Value To All
Sub multiply_all()
' Smart code for Multiply by Input Number to all selection range value
' Smart Excel(anilnahar.com)
Dim rng As Range
Dim c As Integer
c = InputBox("Enter number to multiple", "Value from Multiply ")
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng * c
Else
End If
Next rng
End Sub
Password Breaker Workbook
Sub PasswordBreaker()
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Exit Sub
End If
End Sub
Password Breaker Worksheet
Sub PasswordBreaker()
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Exit Sub
End If
End Sub
Password Protect Without Unprotecting Worksheet
Sub Worksheet_Activate()
Me.Protect Password:=Passwrd
Attempt = 1
Do
sInput = InputBox("Please enter the password for this sheet", "Password Required
Attempt:" & Attempt)
If StrPtr(sInput) = 0 Then
'cancel pressed
Exit Do
Me.Unprotect Password:=Passwrd
Exit Do
Else
Attempt = Attempt + 1
End If
Loop Until Attempt > 3 ' "Don't let the inputbox close if the password is not correct
End Sub
Password Protected Workbook
Sub ProtectWorkbook()
Exit Sub
ErrorOccured:
Exit Sub
End Sub
Password Unprotected Workbook
Sub UnProtectWorkbook()
On Error GoTo ErrorOccured
Dim pwd1 As String, ShtName As String
pwd1 = InputBox("Please Enter the password")
If pwd1 = "" Then Exit Sub
ShtName = "Workbook as a whole"
ActiveWorkbook.Unprotect Password:=pwd1
MsgBox "The workbook's structure has been Unprotected."
Exit Sub
ErrorOccured:
MsgBox "Workbook could not be UnProtected - Password Incorrect"
Exit Sub
End Sub
Pivot Table Update Auto
Sub UpdatePivotTables()
' Smart code for Update auto all pivot table
' Smart Excel(anilnahar.com)
Dim ws As Worksheet
Dim pt As PivotTable
For Each ws In ThisWorkbook.Worksheets
For Each pt In ws.PivotTables
pt.RefreshTable
Next pt
Next ws
End Sub
Print And Print Preview To Area By Input
Sub Print_Area()
Application.DisplayAlerts = False
On Error GoTo 0
Application.DisplayAlerts = True
ans = MsgBox(Prompt:="Click Yes to Print." & vbCrLf & "Click No to Print Preview." &
vbCrLf & "Click Cancel To Abort", Buttons:=vbYesNoCancel, Title:="Print?")
rPrintArea.PrintOut
Else
rPrintArea.PrintOut Preview:=True
End If
End Sub
Print Comments In Last Page
Sub AllCommentsprint()
With ActiveSheet.PageSetup
' Smart code for All Print Comments in Last Page
' Smart Excel(anilnahar.com)
.printComments = xlPrintSheetEnd
End With
End Sub
Print Multiple Selection Range Only
Sub PrintMultiSelection()
' Smart code for Print One More selection range (Select data by Ctrl key)
' Smart Excel(anilnahar.com)
Dim xRng1 As Range
Dim xRng2 As Range
Dim xNewWs As Worksheet
Dim xWs As Worksheet
Dim xIndex As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set xWs = ActiveSheet
Set xNewWs = Worksheets.Add
xWs.Select
xIndex = 1
For Each xRng2 In Selection.Areas
xRng2.Copy
Set xRng1 = xNewWs.Cells(xIndex, 1)
xRng1.PasteSpecial xlPasteValues
xRng1.PasteSpecial xlPasteFormats
xIndex = xIndex + xRng2.Rows.Count
Next
xNewWs.Columns.AutoFit
xNewWs.PrintOut
xNewWs.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Proper Case All
Sub ProperCase()
' Smart code for Convert all in Proper Case by selection range
' Smart Excel(anilnahar.com)
Dim Rng As Range
For Each Rng In Selection
If WorksheetFunction.IsText(Rng) Then
Rng.Value = WorksheetFunction.Proper(Rng.Value)
End If
Next
End Sub
Protect And Unprotect Worksheets
Sub ProtectWS()
' Smart code for Protected Active worksheet by given password
' Smart Excel(anilnahar.com)
ActiveSheet.Protect "smartexcelpassword", True, True
End Sub
---------------------------------------------
Sub UnprotectWS()
' Smart code for Unprotected Active worksheet by given password
' Smart Excel(anilnahar.com)
ActiveSheet.Unprotect "smartexcelpassword"
End Sub
Protect To Other Insert Worksheet
Sub DeleteRows()
xTitleId = "SmartExcel(anilnahar.com)"
Else
End If
End If
Next
DeleteRng.EntireRow.Delete
End Sub
Remove Leading Spaces
Sub RemoveLeadingSpace()
Rng.Value = VBA.LTrim(Rng.Value)
Next
End Sub
Remove Wrap Text
Sub RemoveWrapText()
' Smart code for Remove all wrap text given in columns of active worksheet
Cells.Select
Selection.WrapText = False
Cells.EntireRow.AutoFit
Cells.EntireColumn.AutoFit
End Sub
Rename All Sheets By Entering A Specific Name
Sub ChangeWorkSheetName()
'Smartcode for rename multiple worksheets by the name you want at once
xTitleId = "SmartExcel(anilnahar.com)"
For i = 1 To Application.Sheets.Count
Next
End Sub
Rename Worksheets By A Specific Cell Value
Sub RenameTabs()
'Smartcode for rename multiple worksheets by specific cell value in each worksheet of the
active workbook
For x = 1 To Sheets.Count
Sheets(x).Name = Worksheets(x).Range("A1").Value
End If
Next
End Sub
Repeat Cell Values X Times
Sub CopyData()
xTitleId = "SmartExcel"
xValue = Rng.Range("A1").Value
xNum = Rng.Range("B1").Value
Next
End Sub
Save As Worksheet To Workbook
Sub WS_to_Wb()
'Alter Sheet1 with desire Sheet and Path d:\ also where require
Dim wb As Workbook
Set wb = Workbooks.Add
ThisWorkbook.Sheets("Sheet1").Copy Before:=wb.Sheets(1)
wb.SaveAs "d:\test1.xlsx"
End Sub
---------------------
Sub ActiveSheet_to_Workbook()
'Alter Sheet1 with desire Sheet and Path d:\ also where require
Set wb = Workbooks.Add
ThisWorkbook.Activate
ActiveSheet.Copy Before:=wb.Sheets(1)
wb.Activate
wb.SaveAs "d:\test2.xlsx"
End Sub
Select All Bold Cells In A Range
Sub SelectBold()
'Smartcode for quickly identify and select all cells which have been applied the bold font style
xTitleId = "SmartExcel(www.anilnahar.com)"
If Rng.Font.Bold Then
If OutRng Is Nothing Then
Set OutRng = Rng
Else
Set OutRng = Union(OutRng, Rng)
End If
End If
Next
If Not OutRng Is Nothing Then
OutRng.Select
End If
End Sub
Select Entire Column Except Header
Sub SelectColumn()
'Smartcode for select the entire column except header or the first row in Excel
' Smart Excel(anilnahar.com)
Dim xColIndex As Integer
Dim xRowIndex As Integer
xIndex = Application.ActiveCell.Column
xRowIndex = Application.ActiveSheet.Cells(Rows.Count, xIndex).End(xlUp).Row
Range(Cells(2, xIndex), Cells(xRowIndex, xIndex)).Select
End Sub
Sentance Case Conversion
Sub SentanceCase()
' Smart code for Convert all in Sentance Case i.e. First Capital rest lower
' Smart Excel(anilnahar.com)
Dim Rng As Range
For Each Rng In Selection
If WorksheetFunction.IsText(Rng) Then
Rng.Value = UCase(Left(Rng, 1)) & LCase(Right(Rng, Len(Rng) - 1))
End If
Next Rng
End Sub
Sort Sheets In Alphabetical
Sub SortWs()
' Smart code for Sorting by Ascending/Descending order All worksheet by name
' Smart Excel(anilnahar.com)
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
& "Clicking No will sort in Descending Order", _
vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
If iAnswer = vbYes Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
ElseIf iAnswer = vbNo Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub
Sort Worksheet Tabs By Color
Sub SortWorkBookByColor()
'Smartcode for Sort sheets by colors
Dim xArray1() As Long
Dim xArray2() As String
Dim n As Integer
Application.ScreenUpdating = False
If Val(Application.Version) >= 10 Then
For i = 1 To Application.ActiveWorkbook.Worksheets.Count
If Application.ActiveWorkbook.Worksheets(i).Visible = -1 Then
n = n + 1
ReDim Preserve xArray1(1 To n)
ReDim Preserve xArray2(1 To n)
xArray1(n) = Application.ActiveWorkbook.Worksheets(i).Tab.Color
xArray2(n) = Application.ActiveWorkbook.Worksheets(i).Name
End If
Next
For i = 1 To n
For j = i To n
If xArray1(j) < xArray1(i) Then
temp = xArray2(i)
xArray2(i) = xArray2(j)
xArray2(j) = temp
temp = xArray1(i)
xArray1(i) = xArray1(j)
xArray1(j) = temp
End If
Next
Next
For i = n To 1 Step -1
Application.ActiveWorkbook.Worksheets(CStr(xArray2(i))).Move
after:=Application.ActiveWorkbook.Worksheets(Application.ActiveWorkbook.Worksheets.Count)
Next
End If
Application.ScreenUpdating = True
End Sub
Sorting All Worksheets By Ascending Or Descending
Sub SortWs()
' Smart code for Sorting by Ascending/Descending order All worksheet by name
' Smart Excel(anilnahar.com)
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
& "Clicking No will sort in Descending Order", _
vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
If iAnswer = vbYes Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
ElseIf iAnswer = vbNo Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub
Split A Workbook Into Multiple Workbooks And Save In The Same Folder
Sub Splitbook()
'Smartcode for excel to make new workbook of each worksheet in same folder
' Smart Excel(anilnahar.com)
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Split Cells Into Multiple Rows Based On Carriage Returns
Sub SplitCells()
'Smartcode for Split cells into multiple rows based on carriage returns word by word
' Smart Excel(anilnahar.com)