You are on page 1of 123

Disclaimer

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.

About the Author

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

To the very of the code, before End Sub:

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

' For Substract Value Should be in Negative

' Smart Excel (anilnahar.com)

Dim rng As Range

Dim i As Integer

i = InputBox("Enter number Adding/Substract", "Value from Adding/Substract")

For Each rng In Selection

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

' Smart Excel(anilnahar.com)

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

' Smart Excel(anilnahar.com)

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()

' Smart code for Autofit all columns of Active Worksheet

' Smart Excel(anilnahar.com)

Cells.Select

Cells.EntireColumn.AutoFit

End Sub
Auto Fit Rows

Sub AutoFitRows()

' Smart code for Autofit all rows of Active Worksheet

' Smart Excel(anilnahar.com)

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

' Smart Excel(anilnahar.com)

Application.DisplayAlerts = False

ActiveWorkbook.Save

Application.DisplayAlerts = True

Application.Quit

End Sub
Automatically Invoice Number Generator

Private Sub Workbook_Open()

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

' Smart Excel(anilnahar.com)

Dim rng As Range

Selection.Value = Selection.Value

For Each rng In Selection

If rng = "" Or rng = " " Then

rng.Value = "0"

Else

End If

Next rng

End Sub
Calculator Open

Sub OpenCalculator()

' Smart code for Open Windows Calculator directly

' Smart Excel(anilnahar.com)

Application.ActivateMicrosoftApp Index:=0

End Sub
Change Multiple Field Settings In Pivot Table

Public Sub SetDataFieldsToSum()

'Smart code for Change multiple field settings in pivot table

Dim xPF As PivotField

Dim WorkRng As Range

Set WorkRng = Application.Selection

With WorkRng.PivotTable

.ManualUpdate = True

For Each xPF In .DataFields

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

' Smart Excel(anilnahar.com)

Dim i As Variant

i = InputBox("Please enter your chart title", "Chart Title")

On Error GoTo Last

ActiveChart.SetElement (msoElementChartTitleAboveChart)

ActiveChart.ChartTitle.Text = i

Last:

Exit Sub

End Sub
Combine Duplicate Rows And Sum The Values

Sub CombineRows()

'Smartcode for Sum of Duplicate rows

Dim WorkRng As Range

Dim Dic As Variant

Dim arr As Variant

On Error Resume Next

xTitleId = "SmartExcel(anilnahar.com)"

Set WorkRng = Application.Selection

Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

Set Dic = CreateObject("Scripting.Dictionary")

arr = WorkRng.Value

For i = 1 To UBound(arr, 1)

Dic(arr(i, 1)) = Dic(arr(i, 1)) + arr(i, 2)

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()

'Smartcode for Convert Columns And Rows Into Single Column

Dim Range1 As Range, Range2 As Range, Rng As Range

Dim rowIndex As Integer

xTitleId = "SmartExcel(anilnahar.com)"

Set Range1 = Application.Selection

Set Range1 = Application.InputBox("Source Ranges:", xTitleId, Range1.Address, Type:=8)

Set Range2 = Application.InputBox("Convert to (single cell):", xTitleId, Type:=8)

rowIndex = 0

Application.ScreenUpdating = False

For Each Rng In Range1.Rows

Rng.Copy

Range2.Offset(rowIndex, 0).PasteSpecial Paste:=xlPasteAll, Transpose:=True

rowIndex = rowIndex + Rng.Columns.Count

Next

Application.CutCopyMode = False

Application.ScreenUpdating = True

End Sub
Convert Month Name To Number

Sub ChangeNum()

'Smartcode for Convert month name to number

Dim Rng As Range

Dim WorkRng As Range

On Error Resume Next

xTitleId = "SmartExcel(anilnahar.com)"

Set WorkRng = Application.Selection

Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

For Each Rng In WorkRng

If Rng.Value <> "" Then

Rng.Value = Month(DateValue("03/" & Rng.Value & "/2014"))

End If

Next

End Sub
Convert Negative To Positive Value

Sub convert_positive()

' Smart code for convert Negative value in Positive

' Smart Excel(anilnahar.com)

Dim rng As Range

Selection.Value = Selection.Value

For Each rng In Selection

If WorksheetFunction.IsNumber(rng) Then

rng.Value = Abs(rng)

End If
Convert Number To Month Name

Sub ChangeMonth()

'Smartcode for Convert number to month name

Dim Rng As Range

Dim WorkRng As Range

On Error Resume Next

xTitleId = "SmartExcel(anilnahar.com)"

Set WorkRng = Application.Selection

Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

For Each Rng In WorkRng

Rng.Value = VBA.Format(Rng.Value * 29, "mmmm")

Next

End Sub
Convert One Cell To Multiple Rows

Sub TransposeRange()

'Smartcode for convert once cell data to muliple rows

Dim rng As Range

Dim InputRng As Range, OutRng As Range

xTitleId = "SmartExcel(www.anilnahar.com)"

Set InputRng = Application.Selection.Range("A1")

Set InputRng = Application.InputBox("Range(single cell) :", xTitleId, InputRng.Address,


Type:=8)

Set OutRng = Application.InputBox("Out put to (single cell):", xTitleId, Type:=8)

Arr = VBA.Split(InputRng.Range("A1").Value, <span style="background-color: #ffff00;">","


</span>)

OutRng.Resize(UBound(Arr) - LBound(Arr) + 1).Value = Application.Transpose(Arr)

End Sub
Convert Text To Column

Sub Text_to_Column()

'Smart Code for convert text to column by space separator

'Smart Excel (www.anilnahar.com)

Dim selected_range, selected_range_individual_column() As Range

Dim one_to_how_many_columns, col_count As Long

Set selected_range = Selection

On Error GoTo err_occured:

one_to_how_many_columns = 10

Application.DisplayAlerts = False

If Not (TypeName(selected_range) = "Range") Then End

ReDim selected_range_individual_column(selected_range.Columns.Count - 1) As Range

For col_count = LBound(selected_range_individual_column) To


UBound(selected_range_individual_column)

Set selected_range_individual_column(col_count) = selected_range.Columns(col_count + 1)

Next col_count

For col_count = UBound(selected_range_individual_column) To


LBound(selected_range_individual_column) Step -1

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()

'Smartcode for count words in selected range

Dim xRg As Range

Dim xRgEach As Range

Dim xAddress As String

Dim xRgVal As String

Dim xRgNum As Long

Dim xNum As Long

On Error Resume Next

xAddress = ActiveWindow.RangeSelection.Address

Set xRg = Application.InputBox("Please select a range:", "Smart Excel", xAddress, , , , , 8)

If xRg Is Nothing Then Exit Sub

Application.ScreenUpdating = False

If Application.WorksheetFunction.CountBlank(xRg) = xRg.Count Then

MsgBox "Words In Selection Is: 0", vbInformation, "Smart Excel(www.anilnahar.com)"

Exit Sub

End If

For Each xRgEach In xRg

xRgVal = xRgEach.Value

xRgVal = Application.WorksheetFunction.Trim(xRgVal)

If xRgEach.Value <> "" Then

xNum = Len(xRgVal) - Len(Replace(xRgVal, " ", "")) + 1

xRgNum = xRgNum + xNum

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()

' Smart code for Count Total Words in Activate Worksheet

' Smart Excel(anilnahar.com)

Dim WordCnt As Long

Dim rng As Range

Dim S As String

Dim N As Long

For Each rng In ActiveSheet.UsedRange.Cells

S = Application.WorksheetFunction.Trim(rng.Text)

N = 0

If S <> vbNullString Then

N = Len(S) - Len(Replace(S, " ", "")) + 1

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()

'Smartcode for create a monthly calendar or a yearly calendar in Excel

ActiveSheet.Protect DrawingObjects:=False, Contents:=False, _

Scenarios:=False

Application.ScreenUpdating = False

On Error GoTo MyErrorTrap

Range("a1:g14").Clear

MyInput = InputBox("Type in Month and year for Calendar in format mm/yy ")

If MyInput = "" Then Exit Sub

StartDay = DateValue(MyInput)

If Day(StartDay) <> 1 Then

StartDay = DateValue(Month(StartDay) & "/1/" & _

Year(StartDay))

End If

Range("a1").NumberFormat = "mmmm yyyy"

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

Range("a1").Value = Application.Text(MyInput, "mmmm yyyy")

DayofWeek = Weekday(StartDay)

CurYear = Year(StartDay)

CurMonth = Month(StartDay)

FinalDay = DateSerial(CurYear, CurMonth + 1, 1)

Select Case DayofWeek

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

For Each cell In Range("a3:g8")

RowCell = cell.Row

ColCell = cell.Column

If cell.Column = 1 And cell.Row = 3 Then

ElseIf cell.Column <> 1 Then

If cell.Offset(0, -1).Value >= 1 Then

cell.Value = cell.Offset(0, -1).Value + 1

If cell.Value > (FinalDay - StartDay) Then

cell.Value = ""

Exit For

End If

End If

ElseIf cell.Row > 3 And cell.Column = 1 Then

cell.Value = cell.Offset(-1, 6).Value + 1

If cell.Value > (FinalDay - StartDay) Then

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

With Range("A3").Offset(x * 2, 0).Resize(2, _

7).Borders(xlLeft)

.Weight = xlThick
.ColorIndex = xlAutomatic

End With

With Range("A3").Offset(x * 2, 0).Resize(2, _

7).Borders(xlRight)

.Weight = xlThick

.ColorIndex = xlAutomatic

End With

Range("A3").Offset(x * 2, 0).Resize(2, 7).BorderAround _

Weight:=xlThick, ColorIndex:=xlAutomatic

Next

If Range("A13").Value = "" Then Range("A13").Offset(0, 0) _

.Resize(2, 8).EntireRow.Delete

ActiveWindow.DisplayGridlines = False

ActiveSheet.Protect DrawingObjects:=True, Contents:=True, _

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." _

& Chr(13) & "Spell the Month correctly" _

& " (or use 3 letter abbreviation)" _

& Chr(13) & "and 4 digits for the Year"

MyInput = InputBox("Type in Month and year for Calendar")

If MyInput = "" Then Exit Sub

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()

Dim Rng As Range

Dim maxRows, maxCols, r, c As Integer

Set Rng = Selection

maxRows = Rng.Rows.Count

maxCols = Rng.Columns.Count

For c = 1 To maxCols

r = 1

Do While r <= maxRows

If Len(Dir(ActiveWorkbook.Path & "\" & Rng(r, c), vbDirectory)) = 0 Then

MkDir (ActiveWorkbook.Path & "\" & Rng(r, c))

On Error Resume Next

End If

r = r + 1

Loop

Next c

End Sub
Cube Root To All

Sub CubeRoot()

' Smart code for find Cube root of selection cell

' Smart Excel(anilnahar.com)

Dim rng As Range

Dim i As Integer

For Each rng In Selection

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()

' Smart code for Shown Data Entry Form of Worksheet

' Smart Excel(anilnahar.com)

ActiveSheet.ShowDataForm

End Sub
Delete All Blank Worksheets

Sub deleteallblanksheets()

' Smart code for Delete All Blank Worksheets

' Smart Excel(anilnahar.com)

Dim Ws As Worksheet

On Error Resume Next

Application.ScreenUpdating = False

Application.DisplayAlerts = False

For Each Ws In Application.Worksheets

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()

' Smart code for Delete all worksheets except active

' Smart Excel(anilnahar.com)

Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets

If ws.Name <> ThisWorkbook.ActiveSheet.Name Then

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

' Smart Excel(anilnahar.com)

Selection.Value = Selection.Value

End Sub
Delete Decimal Value

Sub delDecimals()

' Smart code for Delete decimal value in selection range

' Smart Excel(anilnahar.com)

Dim lnumber As Double

Dim lResult As Long

Dim rng As Range

For Each rng In Selection

rng.Value = Int(rng)

rng.NumberFormat = "0"

Next rng

End Sub
Delete Every Other Row In Selection

Sub DeleteEveryOtherRow()

'Smartcode for delete rows with selection range

Dim rng As Range

Dim InputRng As Range

xTitleId = "SmartExcel(anilnahar.com)"

Set InputRng = Application.Selection

Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)

Application.ScreenUpdating = False

For i = InputRng.Rows.Count To 1 Step -2

Set rng = InputRng.Cells(i, 1)

rng.EntireRow.Delete

Next

Application.ScreenUpdating = True

End Sub
Delete Input Value In Range

Sub delvalue()

' Smart code for Delete Input value in selection range

' Smart Excel(anilnahar.com)

Dim Rng As Range

Dim rc As String

rc = InputBox("Character(s) to Replace", "Enter Value")

For Each Rng In Selection

Selection.Replace What:=rc, Replacement:=""

Next

End Sub
Fill Blank Cells With 0 Or Other Specific Value

Sub FillEmptyBlankCellWithValue()

'Smartcode for Enter any value in selection range

Dim cell As Range

Dim InputValue As String

On Error Resume Next

InputValue = InputBox("Enter value that will fill empty cells in selection", _

"Fill Empty Cells")

For Each cell In Selection

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

xTitleId = "SmartExcel Code(anilnahar.com)"

Set Range1 = Application.Selection

Set Range1 = Application.InputBox("Range1 :", xTitleId, Range1.Address, Type:=8)

Set Range2 = Application.InputBox("Range2:", xTitleId, Type:=8)

Application.ScreenUpdating = False

For Each Rng1 In Range1

xValue = Rng1.Value

For Each Rng2 In Range2

If xValue = Rng2.Value Then

If outRng Is Nothing Then

Set outRng = Rng1

Else

Set outRng = Application.Union(outRng, Rng1)

End If

End If

Next

Next

outRng.Select

Application.ScreenUpdating = True

End Sub
Hide All Inactive Worksheets

Sub HideWorksheets()

' Smart code for Hide all worksheets except active

' Smart Excel(anilnahar.com)

Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets

If ws.Name <> ThisWorkbook.ActiveSheet.Name Then

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()

'Smart code for highlight color alternate rows

'Smart Excel (anilnahar.com)

Dim LR As Long, i As Long

'Stop the screen from flickering

Application.ScreenUpdating = False

'Find the last filled row in column A

LR = Range("A" & Rows.Count).End(xlUp).Row

'Loop through the filled rows in steps of 2

For i = 2 To LR Step 2

'Colour alternate rows

Rows(i).EntireRow.Interior.ColorIndex = 6

Next i

'Turn screen updating on again

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

' Change the color by alter number instead of 44(Orange color)

' Smart Excel(anilnahar.com)

Dim myRange As Range

Dim myCell As Range

Set myRange = Selection

For Each myCell In myRange

If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then

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

' Change the color by alter number instead of 44(Orange color)

' Smart Excel(anilnahar.com)

Dim myRange As Range

Dim myCell As Range

Set myRange = Selection

For Each myCell In myRange

If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then

myCell.Interior.ColorIndex = 44

End If

Next myCell

End Sub
Highlight Highest Value

Sub Maxvalue()

' Smart code for Color Maximum value in selection range

' Smart Excel(anilnahar.com)

Dim rng As Range

For Each rng In Selection

If rng = WorksheetFunction.Max(Selection) Then

rng.Style = "Good"

End If

Next rng

End Sub
Highlight Lowest Value

Sub MinValue()

' Smart code for Color Minimum value in selection range

' Smart Excel(anilnahar.com)

Dim rng As Range

For Each rng In Selection

If rng = WorksheetFunction.Min(Selection) Then

rng.Style = "Good"

End If

Next rng

End Sub
Highlight Mispelled Cell Text

Sub HighlightMispelledCells()

'Smart code for highlight misspelled text cell

'Smart Excel (www.anilnahar.com)

For Each cl In ActiveSheet.UsedRange

If Not Application.CheckSpelling(Word:=cl.Text) Then _

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

' Smart Excel(anilnahar.com)

Dim RangeName As Name

Dim HighlightNameRange As Range

On Error Resume Next

For Each RangeName In ActiveWorkbook.Names

Set HighlightNameRange = RangeName.RefersToRange

HighlightNameRange.Interior.ColorIndex = 36

Next RangeName

End Sub
Highlight Negative Number

Sub highlightNegativeNumbers()

' Smart code for highlight colors of negative number in selection range

' Change the color by alter number in Font.color

' Smart Excel(anilnahar.com)

Dim Rng As Range

For Each Rng In Selection

If WorksheetFunction.IsNumber(Rng) Then

If Rng.Value < 0 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

' Smart Excel (anilnahar.com)

Dim xStr As String

Dim xRg As Range

Dim xTxt As String

Dim xCell As Range

Dim xChar As String

Dim I As Long

Dim J As Long

On Error Resume Next

If ActiveWindow.RangeSelection.Count > 1 Then

xTxt = ActiveWindow.RangeSelection.AddressLocal

Else

xTxt = ActiveSheet.UsedRange.AddressLocal

End If

LInput:

Set xRg = Application.InputBox("please select the data range:",


"SmartExcel(anilnahar.com)", xTxt, , , , , 8)

If xRg Is Nothing Then Exit Sub

If xRg.Areas.Count > 1 Then

MsgBox "not support multiple columns"

GoTo LInput

End If

If xRg.Columns.Count <> 2 Then

MsgBox "the selected range can only contain two columns "

GoTo LInput

End If

For I = 0 To xRg.Rows.Count - 1

xStr = xRg.Range("B1").Offset(I, 0).Value

With xRg.Range("A1").Offset(I, 0)
.Font.ColorIndex = 1

For J = 1 To Len(.Text)

If Mid(.Text, J, Len(xStr)) = xStr Then .Characters(J, Len(xStr)).Font.ColorIndex = 3

Next

End With

Next I

End Sub
Highlight Unique Value

Sub ColorUnique()

' Smart code for Color Unique value in selection range

' Smart Excel(anilnahar.com)

Dim rng As Range

Set rng = Selection

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()

' Smart code for Create Image of Active Chart of WorkSheet

' Smart Excel(anilnahar.com)

ActiveChart.ChartArea.Copy

ActiveSheet.Range("A1").Select

ActiveSheet.Pictures.Paste.Select

End Sub
Image Linked Of Selction Area

Sub LinkedImage()

' Smart code for Create Image of With linking

' Smart Excel(anilnahar.com)

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()

'Smart Code for Import All files of folder in worksheet

'Smart Excel (www.anilnahar.com)

Set folder = Application.FileDialog(msoFileDialogFolderPicker)

If folder.Show <> -1 Then Exit Sub

xDir = folder.SelectedItems(1)

Call ListFilesInFolder(xDir, True)

End Sub

Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)

Dim xFileSystemObject As Object

Dim xFolder As Object

Dim xSubFolder As Object

Dim xFile As Object

Dim rowIndex As Long

Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")

Set xFolder = xFileSystemObject.GetFolder(xFolderName)

rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1

For Each xFile In xFolder.Files

Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name

rowIndex = rowIndex + 1

Next xFile

If xIsSubfolders Then

For Each xSubFolder In xFolder.SubFolders

ListFilesInFolder xSubFolder.Path, True

Next xSubFolder

End If

Set xFile = Nothing

Set xFolder = Nothing

Set xFileSystemObject = Nothing

End Sub

Function GetFileOwner(ByVal xPath As String, ByVal xName As String)

Dim xFolder As Object

Dim xFolderItem As Object


Dim xShell As Object

xName = StrConv(xName, vbUnicode)

xPath = StrConv(xPath, vbUnicode)

Set xShell = CreateObject("Shell.Application")

Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))

If Not xFolder Is Nothing Then

Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))

End If

If Not xFolderItem Is Nothing Then

GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)

Else

GetFileOwner = ""

End If

Set xShell = Nothing

Set xFolder = Nothing

Set xFolderItem = Nothing

End Function
Import Multiple Text Files

Sub MulipleTextFiles()

'SmartCode for Insert Multiple text file in Seoarate worksheets

'SmartExcel(www.anilnahar.com)

Dim xFilesToOpen As Variant

Dim I As Integer

Dim xWb As Workbook

Dim xTempWb As Workbook

Dim xDelimiter As String

Dim xScreen As Boolean

On Error GoTo ErrHandler

xScreen = Application.ScreenUpdating

Application.ScreenUpdating = False

xDelimiter = "|"

xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Smart Excel", ,


True)

If TypeName(xFilesToOpen) = "Boolean" Then

MsgBox "No files were selected", , "Smart Excel"

GoTo ExitHandler

End If

I = 1

Set xTempWb = Workbooks.Open(xFilesToOpen(I))

xTempWb.Sheets(1).Copy

Set xWb = Application.ActiveWorkbook

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:="|"

Do While I < UBound(xFilesToOpen)


I = I + 1

Set xTempWb = Workbooks.Open(xFilesToOpen(I))

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

Set xWb = Nothing

Set xTempWb = Nothing

Exit Sub

ErrHandler:

MsgBox Err.Description, , "SmartExcel(www.anilnahar.com)"

Resume ExitHandler

End Sub


Index Worksheets With Hyperlink
Sub IndexingWs()

' Smart code for Create Index all worksheet with Hyperlink

' Smart Excel(anilnahar.com)

Dim i As Long

On Error Resume Next

Application.DisplayAlerts = False

Worksheets("Table of Content").Delete

Application.DisplayAlerts = True

On Error GoTo 0

ThisWorkbook.Sheets.Add before:=ThisWorkbook.Worksheets(1)

ActiveSheet.Name = "Table of Content"

For i = 1 To Sheets.Count

With ActiveSheet

.Hyperlinks.Add _

Anchor:=ActiveSheet.Cells(i, 1), _

Address:="", _

SubAddress:="'" & Sheets(i).Name & "'!A1", _

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

' Smart Excel(anilnahar.com)

Dim ws As Worksheet

Dim nmToc As Name

Dim rng1 As Range

Dim lngProceed As Boolean

Dim bNonWkSht As Boolean

Dim lngSht As Long

Dim lngShtNum As Long

Dim strWScode As String

Dim vbCodeMod

'Summary of ActiveWorkbook

If ActiveWorkbook Is Nothing Then

MsgBox "You must have a workbook open first!", vbInformation, "No Open Book"

Exit Sub

End If

'Turn off events for fast macro run

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

On Error Resume Next

Set nmToc = ActiveWorkbook.Names("TOC_Index")

If Not nmToc Is Nothing Then

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)

'Add the marker range name

ActiveWorkbook.Names.Add "TOC_INDEX", ws.[a1]

ws.Name = "TOC_Index"

On Error GoTo 0

On Error GoTo ErrHandler

For lngSht = 2 To ActiveWorkbook.Sheets.Count

'set to start at A6 of TOC sheet

'Test sheets to determine whether they are normal worksheets

ws.Cells(lngSht + 4, 2).Value = TypeName(ActiveWorkbook.Sheets(lngSht))

If TypeName(ActiveWorkbook.Sheets(lngSht)) = "Worksheet" Then

'Add hyperlinks to normal worksheets

ws.Hyperlinks.Add Anchor:=ws.Cells(lngSht + 4, 1), Address:="", SubAddress:="'" &


ActiveWorkbook.Sheets(lngSht).Name & "'!A1",
TextToDisplay:=ActiveWorkbook.Sheets(lngSht).Name

Else

'Add name of any non-worksheets

ws.Cells(lngSht + 4, 1).Value = ActiveWorkbook.Sheets(lngSht).Name

'Colour these sheets yellow

ws.Cells(lngSht + 4, 1).Interior.Color = vbYellow

ws.Cells(lngSht + 4, 2).Font.Italic = True

bNonWkSht = True

End If

Next lngSht

'Add headers and formatting

With ws
With .[a1:a4]

.Value = Application.Transpose(Array(ActiveWorkbook.Name, "", Format(Now(), "dd-mmm-yy


hh:mm"), ActiveWorkbook.Sheets.Count - 1 & " sheets"))

.Font.Size = 14

.Cells(1).Font.Bold = True

End With

With .[a6].Resize(lngSht - 1, 1)

.Font.Bold = True

.Font.ColorIndex = 41

.Resize(1, 2).EntireColumn.HorizontalAlignment = xlLeft

.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

strWScode = "Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As


Boolean)" & vbCrLf _

& " Dim rng1 As Range" & vbCrLf _

& " Set rng1 = Intersect(Target, Range([a6], Cells(Rows.Count, 1).End(xlUp)))" & vbCrLf _

& " If rng1 Is Nothing Then Exit Sub" & vbCrLf _

& " On Error Resume Next" & vbCrLf _

& " If Target.Cells(1).Offset(0, 1) <> ""Worksheet"" Then Sheets(Target.Value).Activate" &


vbCrLf _

& " If Err.Number <> 0 Then MsgBox ""Could not select sheet"" & Target.Value" & vbCrLf _

& "End Sub" & vbCrLf

Set vbCodeMod = ActiveWorkbook.VBProject.VBComponents(ws.CodeName)

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()

Dim xRow As Long

Dim xDirect$, xFname$, InitialFoldr$

InitialFoldr$ = "D:\" '<<< Startup folder to begin searching from

With Application.FileDialog(msoFileDialogFolderPicker)

.InitialFileName = Application.DefaultFilePath & "\"

.Title = "Please select a folder to list Files from"

.InitialFileName = InitialFoldr$

.Show

If .SelectedItems.Count <> 0 Then

xDirect$ = .SelectedItems(1) & "\"

xFname$ = Dir(xDirect$, 7)

Do While xFname$ <> ""

ActiveCell.Offset(xRow) = xFname$

xRow = xRow + 1

xFname$ = Dir

Loop

End If

End With

End Sub
Insert Worksheets

Sub InsertSheets()

' Smart code for Insert number of worksheets by input box

' Smart Excel(anilnahar.com)

Dim i As Integer

i = InputBox("Enter number of sheets to insert.", "Enter Multiple Sheets")

Sheets.Add After:=ActiveSheet, Count:=i

End Sub


Insert Columns

Sub InsertColumns()

' Smart code for Insert columns by input no of columns require from select cell

' Smart Excel(anilnahar.com)

Dim i As Integer

Dim c As Integer

ActiveCell.EntireColumn.Select

On Error GoTo Last

i = InputBox("Enter number of columns to insert", "Insert Columns")

For c = 1 To i

Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromRightorAbove

Next c

Last: Exit Sub

End Sub
Insert Header And Footer By Input Text

Sub InputHeader()

Dim Text As String

' Smart code for insert text in center of header by input value

' Smart Excel(anilnahar.com)

Text = InputBox("Enter your text here", "Enter Text")

With ActiveSheet.PageSetup

.LeftHeader = ""

.CenterHeader = Text

.RightHeader = ""

.LeftFooter = ""

.CenterFooter = ""

.RightFooter = ""

End With

End Sub
Insert Header And Footer Current Date

Sub InputHeader()

Dim Text As String

' Smart code for insert text in center of header by input value

' Smart Excel(anilnahar.com)

Text = InputBox("Enter your text here", "Enter Text")

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

' Smart Excel(anilnahar.com)

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

' Smart Excel(anilnahar.com)

Dim Rng As Range

For Each Rng In Selection

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

On Error Resume Next

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.Offset(1, 0).Resize(Selection.Rows.Count - 1).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()

'Breaks workbook password protection.

Dim i As Integer, j As Integer, k As Integer

Dim l As Integer, m As Integer, n As Integer

Dim i1 As Integer, i2 As Integer, i3 As Integer

Dim i4 As Integer, i5 As Integer, i6 As Integer

On Error Resume Next

For i = 65 To 66: For j = 65 To 66: For k = 65 To 66

For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66

For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66

For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126

ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _

Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _

Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)

If ThisWorkbook.ProtectStructure = False Then

MsgBox "One usable password is " & Chr(i) & Chr(j) & _

Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _

Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)

Exit Sub

End If

Next: Next: Next: Next: Next: Next

Next: Next: Next: Next: Next: Next

End Sub
Password Breaker Worksheet

Sub PasswordBreaker()

'Breaks worksheet password protection.

Dim i As Integer, j As Integer, k As Integer

Dim l As Integer, m As Integer, n As Integer

Dim i1 As Integer, i2 As Integer, i3 As Integer

Dim i4 As Integer, i5 As Integer, i6 As Integer

On Error Resume Next

For i = 65 To 66: For j = 65 To 66: For k = 65 To 66

For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66

For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66

For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126

ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _

Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _

Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)

If ActiveSheet.ProtectContents = False Then

MsgBox "One usable password is " & Chr(i) & Chr(j) & _

Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _

Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)

Exit Sub

End If

Next: Next: Next: Next: Next: Next

Next: Next: Next: Next: Next: Next

End Sub
Password Protect Without Unprotecting Worksheet

Sub Worksheet_Activate()

Const Passwrd As String = "abc123"

Dim sInput As Variant

Dim Attempt As Integer

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

ElseIf sInput = Passwrd Then ' Valid Password

Me.Unprotect Password:=Passwrd

Exit Do

Else

MsgBox "Invalid Password", 48, "Invalid"

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()

On Error GoTo ErrorOccured

Dim pwd1 As String, ShtName As String

pwd1 = InputBox(&quot;Please Enter the password&quot;)

If pwd1 = &quot;&quot; Then Exit Sub

ShtName = &quot;Workbook as a whole&quot;

ActiveWorkbook.Protect Structure:=True, Windows:=False, Password:=pwd1

MsgBox &quot;The workbook's structure has been protected.&quot;

Exit Sub

ErrorOccured:

MsgBox &quot;Workbook could not be Protected&quot;

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()

'Smart Code for Print and Print Preview to selection Area

' Smart Excel (anilnahar.com)

Dim ans As String, rPrintArea As Range

On Error Resume Next

Application.DisplayAlerts = False

Set rPrintArea = Application.InputBox(Prompt:="Use Mouse to select area to Print.",


Title:="Select Print Area", Type:=8)

On Error GoTo 0

Application.DisplayAlerts = True

If rPrintArea Is Nothing Then Exit Sub

ans = MsgBox(Prompt:="Click Yes to Print." & vbCrLf & "Click No to Print Preview." &
vbCrLf & "Click Cancel To Abort", Buttons:=vbYesNoCancel, Title:="Print?")

If ans = vbCancel Then Exit Sub

If ans = vbYes Then

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

Private Sub Workbook_NewSheet(ByVal Sh As Object)


'Smart Code for Protection Insert Worksheet
' Smart Excel (anilnahar.com)

With Application
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Sh.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End With
MsgBox "disable to add sheets"
End Sub

Remove Blank Rows Of The Selected Range

Sub DeleteBlankRows()
'Smart code for delete all blank rows given range
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "Smart Excel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
xRows = WorkRng.Rows.Count
Application.ScreenUpdating = False
For i = xRows To 1 Step -1
If Application.WorksheetFunction.CountA(WorkRng.Rows(i)) = 0 Then
WorkRng.Rows(i).EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
End If
Next
Application.ScreenUpdating = True
End Sub
Remove Entire Rows Based On Cell Value

Sub DeleteRows()

'Smartcode for delete rows on input value by selection range

Dim rng As Range

Dim InputRng As Range

Dim DeleteRng As Range

Dim DeleteStr As String

xTitleId = "SmartExcel(anilnahar.com)"

Set InputRng = Application.Selection

Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)

DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)

For Each rng In InputRng

If rng.Value = DeleteStr Then

If DeleteRng Is Nothing Then

Set DeleteRng = rng

Else

Set DeleteRng = Application.Union(DeleteRng, rng)

End If

End If

Next

DeleteRng.EntireRow.Delete

End Sub
Remove Leading Spaces

Sub RemoveLeadingSpace()

'Remove space on leading side only

Dim Rng As Range

Dim WorkRng As Range

On Error Resume Next

xTitleId = "SmartExcel Code(anilnahar.com)"

Set WorkRng = Application.Selection

Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

For Each Rng In WorkRng

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

' Smart Excel(anilnahar.com)

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

' Smart Excel(anilnahar.com)

Dim Rng As Range

Dim WorkRng As Range

On Error Resume Next

xTitleId = "SmartExcel(anilnahar.com)"

newName = Application.InputBox("Name", xTitleId, "", Type:=2)

For i = 1 To Application.Sheets.Count

Application.Sheets(i).Name = newName & i

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

' Smart Excel(anilnahar.com)

For x = 1 To Sheets.Count

If Worksheets(x).Range("A1").Value <> "" Then

Sheets(x).Name = Worksheets(x).Range("A1").Value

End If

Next

End Sub
Repeat Cell Values X Times

Sub CopyData()

'Smartcode for repeat cell value on giving times

' Smart Excel(anilnahar.com)

Dim Rng As Range

Dim InputRng As Range, OutRng As Range

xTitleId = "SmartExcel"

Set InputRng = Application.Selection

Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)

Set OutRng = Application.InputBox("Out put to (single cell):", xTitleId, Type:=8)

Set OutRng = OutRng.Range("A1")

For Each Rng In InputRng.Rows

xValue = Rng.Range("A1").Value

xNum = Rng.Range("B1").Value

OutRng.Resize(xNum, 1).Value = xValue

Set OutRng = OutRng.Offset(xNum, 0)

Next

End Sub
Save As Worksheet To Workbook

Sub WS_to_Wb()

'Smart Code for Save as Specific Worksheet to Workbook

'Smart Code (www.anilnahar.com)

'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()

'Smart Code for Save as Active Worksheet to Workbook

'Smart Code (www.anilnahar.com)

'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

Dim Rng As Range

Dim WorkRng As Range

Dim OutRng As Range

On Error Resume Next

xTitleId = "SmartExcel(www.anilnahar.com)"

Set WorkRng = Application.Selection

Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

For Each Rng In WorkRng

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)

Dim Rng As Range


Dim WorkRng As Range
On Error Resume Next
xTitleId = "SmartExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
For Each Rng In WorkRng
lLFs = VBA.Len(Rng) - VBA.Len(VBA.Replace(Rng, vbLf, ""))
If lLFs > 0 Then
Rng.Offset(1, 0).Resize(lLFs).Insert shift:=xlShiftDown
Rng.Resize(lLFs + 1).Value = Application.WorksheetFunction.Transpose(VBA.Split(Rng,
vbLf))
End If
Next
End Sub

Split Data Into Multiple Worksheets Based On Column

' Smart code for Split data into multiple worksheet by column
' Smart Excel(anilnahar.com)

Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vcol = 1
Set ws = Sheets("Sheet1")
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:C1"
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol),
ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr =
Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub





====================

Note: In the above code:

vcol =1, the number 1 is the column number that you want to split the data based on.

Set ws = Sheets("Sheet1"), Sheet1 is the sheet name that you want to apply this code.

title = "A1:C1", A1:C1 is the range of the title.

All of them are variables, you can change them as your need.

Split Data Into Multiple Worksheets By Rows Count

Sub SplitData()
' Smartcode for split data into multiple worksheets by row count
' Smart Excel(anilnahar.com)
Dim WorkRng As Range
Dim xRow As Range
Dim SplitRow As Integer
Dim xWs As Worksheet
On Error Resume Next
xTitleId = "SmartExcel(www.anilnahar.com)"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
SplitRow = Application.InputBox("Split Row Num", xTitleId, 5, Type:=1)
Set xWs = WorkRng.Parent
Set xRow = WorkRng.Rows(1)
Application.ScreenUpdating = False
For i = 1 To WorkRng.Rows.Count Step SplitRow
resizeCount = SplitRow
If (WorkRng.Rows.Count - xRow.Row + 1) < SplitRow Then resizeCount =
WorkRng.Rows.Count - xRow.Row + 1
xRow.Resize(resizeCount).Copy
Application.Worksheets.Add after:=Application.Worksheets(Application.Worksheets.Count)
Application.ActiveSheet.Range("A1").PasteSpecial
Set xRow = xRow.Offset(SplitRow)
Next
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Split Word Or Number Into Separate Cells

Sub Splitword()
'Smartcode for splitword into separate cell by each character
Dim Rng As Range
Dim InputRng As Range, OutRng As Range
xTitleId = "SmartExcel(anilnahar.com)"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
Set OutRng = Application.InputBox("Out put to (single cell):", xTitleId, Type:=8)
Application.ScreenUpdating = False
For Each Rng In InputRng
xValue = Rng.Value
xRow = Rng.Row
For i = 1 To VBA.Len(xValue)
OutRng.Cells(xRow, i).Value = VBA.Mid(xValue, i, 1)
Next
Next
Application.ScreenUpdating = True
End Sub

Square Root To All

Sub SquareRoot()
' Smart code for find Square root of selection cell
' Smart Excel(anilnahar.com)

Dim rng As Range
Dim i As Integer
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
rng.Value = Sqr(rng)
Else
End If
Next rng
End Sub

Status Bar Progress

Sub StatusBar()
' Smart code for shown progress in status bar by insert value 1 to 10000 in column
' Smart Excel(anilnahar.com)

Application.StatusBar = "Start Printing the Numbers"
For icntr = 1 To 10000
Cells(icntr, 1) = icntr
Application.StatusBar = " Please wait while printing the numbers " & Round((icntr / 10000 *
100), 0) & "%"
Next
Application.StatusBar = ""
End Sub
Swap Two Nonadjacent Cell Contents

Sub SwapTwoRange()
'Smartcode for Swap Two Nonadjacent Cell Contents
' Smart Excel(anilnahar.com)

Dim Rng1 As Range, Rng2 As Range
Dim arr1 As Variant, arr2 As Variant
xTitleId = "SmartExcel(anilnahar.com)"
Set Rng1 = Application.Selection
Set Rng1 = Application.InputBox("Range1:", xTitleId, Rng1.Address, Type:=8)
Set Rng2 = Application.InputBox("Range2:", xTitleId, Type:=8)
Application.ScreenUpdating = False
arr1 = Rng1.Value
arr2 = Rng2.Value
Rng1.Value = arr2
Rng2.Value = arr1
Application.ScreenUpdating = True
End Sub

Unhide All Hidden Worksheets

Sub UnhideAllSheets()

'Smartcode for unhide all worksheets in workbook
' Smart Excel(anilnahar.com)

Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws
End Sub

------------------
Sub UnhideWorksheet()
' Smart code for Unhide all worksheets except
' Smart Excel(anilnahar.com)

Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws
End Sub
Unhide All Rows And Columns

Sub UnhideRowsColumns()
' Smart code for Unhide all hidden row & column
' Smart Excel(anilnahar.com)

Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
End Sub
Unmerge Cells
Sub UnmergeCells()
' Smart code for remove merge cells from Active cell selection
' Smart Excel(anilnahar.com)
Selection.UnMerge
End Sub
Upper Case All

Sub UpperCase()
' Smart code for Convert all in Upper Case by selection range
' Smart Excel(anilnahar.com)
Dim Rng As Range
For Each Rng In Selection
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value = UCase(Rng)
End If
Next
End Sub
Wrap Text Of Selection Range

Sub WrapText()
' Smart code for wrap text all rows and columns of active worksheet
' Smart Excel(anilnahar.com)

Cells.Select
Selection.WrapText = True
Cells.EntireRow.AutoFit
Cells.EntireColumn.AutoFit
End Sub

You might also like