Вы находитесь на странице: 1из 30

Delete Blank Rows in Excel

Sub DeleteEmptyRows()
'
'This macro will delete all rows, which are missing data in a
'particular column, underneath and including the selected cell.
'
Dim Counter
Dim i As Integer

Counter = InputBox("Enter the total number of rows to process")


ActiveCell.Select
For i = 1 To Counter
If ActiveCell = "" Then
Selection.EntireRow.Delete
Counter = Counter - 1
Else
ActiveCell.Offset(1, 0).Select
End If

Next i

End Sub

Delete Empty Columns (Excel 2007)

Sub Delete_Empty_Columns()

first = Selection.Column
last = Selection.Columns(Selection.Columns.Count).Column

For i = last To first Step -1

If WorksheetFunction.CountBlank(ActiveSheet.Columns(i)) = 1048576
Then
Columns(i).Delete
End If

Next i

End Sub

Delete Empty Columns (Previous Versions of Excel)


Sub Delete_Empty_Columns()

first = Selection.Column
last = Selection.Columns(Selection.Columns.Count).Column
For i = last To first Step -1

If WorksheetFunction.CountBlank(ActiveSheet.Columns(i)) = 65536 Then


Columns(i).Delete
End If

Next i

End Sub

Sort Worksheet Tabs - Ascending or Descending Order

Sub Sort_Worksheets()

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

Bubble Sort Macro in Excel

Sub bubble_sort()

Dim sortingArray As Variant, i As Long, j As Long, temp As Variant

sortingArray = Selection.Value

For i = 1 To (UBound(sortingArray, 1) - 1)
For j = i To UBound(sortingArray, 1)
If Val(sortingArray(j, 1)) < Val(sortingArray(i, 1)) Then
temp = sortingArray(i, 1)
sortingArray(i, 1) = sortingArray(j, 1)
sortingArray(j, 1) = temp
End If
Next j
Next i

Selection.Value = sortingArray

End Sub

Reverse Rows or Columns in a Worksheet

Public Sub Reverse_Rows_or_Columns()

'This Macro will reverse a selection of rows or columns.


'Note: you cannot select an etire row or column, but one
'cell less than that will work fine.
'Don't forget to assign this macro a keyboard shortcut or
'a toolbar button.

Dim Arr() As Variant


Dim Rng As Range
Dim C As Range
Dim Rw As Long
Dim Cl As Long

On Error GoTo EndMacro

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Set Rng = Selection


Rw = Selection.Rows.Count
Cl = Selection.Columns.Count
If Rw > 1 And Cl > 1 Then
MsgBox "Must select either a range of rows or columns, but not
simultaneaously columns and rows.", _
vbExclamation, "Reverse Rows or Columns"
Exit Sub
End If

If Rng.Cells.Count = ActiveCell.EntireRow.Cells.Count Then


MsgBox "Can't select an entire row, only up to one cell less than an
entire row.", vbExclamation, _
"Reverse Rows or Columns"
Exit Sub
End If
If Rng.Cells.Count = ActiveCell.EntireColumn.Cells.Count Then
MsgBox "Can't select an entire column, only up to one cell less than an
entire column.", vbExclamation, _
"Reverse Rows or Columns"
Exit Sub
End If
If Rw > 1 Then
ReDim Arr(Rw)
Else
ReDim Arr(Cl)
End If

Rw = 0
For Each C In Rng
Arr(Rw) = C.Formula
Rw = Rw + 1
Next C

Rw = Rw - 1
For Each C In Rng
C.Formula = Arr(Rw)
Rw = Rw - 1
Next C

EndMacro:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True

End Sub

Reverse Cell Contents (Mirror)

Sub Reverse_Cell_Contents()

If Not ActiveCell.HasFormula Then


sRaw = ActiveCell.Text
sNew = ""
For j = 1 To Len(sRaw)
sNew = Mid(sRaw, j, 1) + sNew
Next j
ActiveCell.Value = sNew
End If
End Sub

Excel Macro to Filter Data to Display the Results that Begin With
Specified Text or Words in Excel - AutoFilter

Sub AutoFilter_Begins_With()
'Put the * mark after the word in which you would like to filter for
this macro

Range("A1").AutoFilter Field:=1, Criteria1:="Enter Criteria Here*"

End Sub
Excel Macro to Filter Data to Show Only the Bottom 10 Items in
Excel - AutoFilter

Sub AutoFilter_Bottom_10_Items()

Range("A1").AutoFilter Field:=1, Criteria1:="10",


Operator:=xlBottom10Items

End Sub

Excel Macro to Filter Data to Show the Bottom 10 Percent of a Data


Set in Excel - AutoFilter

Sub AutoFilter_Bottom_10_Percent()

Range("A1").AutoFilter Field:=1, Criteria1:="10",


Operator:=xlBottom10Percent

End Sub

Excel Macro to Filter Data to Show the Bottom X Number of Items


in Excel - AutoFilter

Sub AutoFilter_Bottom_X_Number_Items()
'Replace the "#" sign with the bottom number of items you would like to
have displayed

Range("A1").AutoFilter Field:=1, Criteria1:="#",


Operator:=xlBottom10Items

End Sub

Excel Macro to Filter Data to Show the Bottom X Percent of the


Data Set in Excel - AutoFilter

Sub AutoFilter_Bottom_X_Percent_Items()
'Replace the "#" sign with the bottom percentage of items you would
like to have displayed

Range("A1").AutoFilter Field:=1, Criteria1:="#",


Operator:=xlBottom10Percent

End Sub

Excel Macro to Display Filter Arrows in a Table or Data Set in Excel


- AutoFilter
Sub AutoFilter_Display_Remove()
'This macro only displays the autofilter arrows and does not perform
any filtering

Range("A1").AutoFilter

End Sub

Excel Macro to Filter Data in Excel - AutoFilter

Sub AutoFilter_in_Excel()

Range("A1").AutoFilter Field:=1, Criteria1:="Enter Criteria Here"

End Sub

Excel Macro to Filter Data in Excel to Show Rows/Data That Meet


Multiple Criteria for One Field - AutoFilter

Sub AutoFilter_in_Excel_AND_Operator_One_Field()

Range("A1").AutoFilter Field:=1, Criteria1:="Enter Criteria Here",


Operator:=xlAnd, Criteria2:="Enter Criteria Here"

End Sub

Excel Macro to Filter Data in Excel to Display Records that Contain


a Value Between Two Values - AutoFilter.

Sub AutoFilter_in_Excel_Above_Below_Num()
'This autofilter macro displays records with a number between 50000 and
75000 within the first field - in this case in column A
'It is important to retain the ">" and "<" signs within this macro
because that it what makes this work correctly

Range("A1").AutoFilter Field:=1, Criteria1:=">50000", Operator:=xlAnd,


Criteria2:="<75000"

End Sub

Excel Macro to Filter Data Sets on Multiple Columns with Multiple


Criteria at Once in Excel - AutoFilter

Sub AutoFilter_in_Excel_Multiple_Col_Filter()

Range("A1").AutoFilter Field:=1, Criteria1:="Enter Criteria Here"

Range("A1").AutoFilter Field:=2, Criteria1:="Enter Criteria Here"


End Sub

Excel Macro to Filter Data in Excel Without the Filter "Arrow"


Appearing in the Filtered Column - AutoFilter

Sub AutoFilter_in_Excel_No_Arrow()
'This option is a bit finicky depending on how many of the fields you
want the drop-down arrow to not be displayed over.
'By default, the visibledropdown option being set to false will only
remove the drop-down arrow from the frield(s) being filtered.

Range("A1").AutoFilter Field:=1, Criteria1:="Enter Criteria Here",


VisibleDropDown:=False

End Sub

Excel Macro to Filter Data in Excel to Display Results that Contain


1 of 2 Possible Values - AutoFilter

Sub AutoFilter_in_Excel_OR_Operator_One_Field()

Range("A1").AutoFilter Field:=1, Criteria1:="Enter Criteria Here",


Operator:=xlOr, Criteria2:="Enter Criteria Here"

End Sub

Excel Macro to Remove All Filtering From a Worksheet in Excel

Sub AutoFilter_Remove()
'This macro removes any filtering in order to display all of the data
but it does not remove the filter arrows

ActiveSheet.ShowAllData

End Sub

Excel Macro to Filter Data to Show the Top 10 Items from a Data
Set in Excel - AutoFilter

Sub AutoFilter_Top_10_Items()

Range("A1").AutoFilter Field:=1, Criteria1:="10", Operator:=xlTop10Items

End Sub

Excel Macro to Filter Data to Show the Top 10 Percent of the Data
Set in Excel - AutoFilter
Sub AutoFilter_Top_10_Percent()

Range("A1").AutoFilter Field:=5, Criteria1:="10",


Operator:=xlTop10Percent

End Sub

Excel Macro to Filter Data in Excel to Show Only the Top 10


Percent of that Data Set - AutoFilter

Sub AutoFilter_Top_X_Percent_Items()
'Replace the "#" sign with the top percentage of items you would like
to have displayed

Range("A1").AutoFilter Field:=1, Criteria1:="#",


Operator:=xlTop10Percent

End Sub

Excel Macro to Filter Data to Show the Top X Number of Items in


Excel - AutoFilter

Sub AutoFilter_Top_X_Number_Items()
'Replace the "#" sign with the top number of items you would like to
have displayed

Range("A1").AutoFilter Field:=1, Criteria1:="#", Operator:=xlTop10Items

End Sub

Excel Macro to Sort Data that Doesn't Have Headers in Ascending


Order in Excel

Sub Sort_Ascending_Basic()
'Sorts a worksheet in ascending order and assumes there are no headers
on the data

Range("A1:C56").Sort _
Key1:=Range("A1"), Header:=xlNo

End Sub

Excel Macro to Sort Data With Headers in Ascending Order in


Excel

Sub Sort_Ascending_With_Header()
'Sorts a worksheet in ascending order and assumes there are headers on
the data
Range("A1:C56").Sort _
Key1:=Range("A1"), Header:=xlYes

End Sub

Excel Macro to Sort Data that Doesn't Have Headers in Descending


Order in Excel

Sub Sort_Descending_Basic()
'Sorts a worksheet in descending order and assumes there are no headers
on the data

Range("A1:C56").Sort _
Key1:=Range("A1"), Order1:=xlDescending, Header:=xlNo

End Sub

Excel Macro to Sort Data With Headers in Descending Order

Sub Sort_Descending_Basic_With_Header()
'Sorts a worksheet in descending order and assumes there are headers on
the data

Range("A1:C56").Sort _
Key1:=Range("A1"), Order1:=xlDescending, Header:=xlYes

End Sub

Excel Macro to Perform a Basic Web Query in Excel and Import


Data from the Web into Excel

Sub Basic_Web_Query()

With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://finance.yahoo.com/q?s=goog", Destination:=Range("$A$1"))
.Name = "q?s=goog_2"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "1,2"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With

End Sub

Email Current Workbook & or Other Attachments

Sub Send_Email_Current_Workbook()

Dim OutApp As Object


Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")


OutApp.Session.Logon
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next


With OutMail
.To = "JOHNDOE@TEST.COM"
.CC = "ADD TEXT HERE"
.BCC = "ADD TEXT HERE"
.Subject = "ADD TEXT HERE - Subject"
.Body = "ADD TEXT HERE"
.Attachments.Add ActiveWorkbook.FullName

.Send
End With
On Error GoTo 0

Set OutMail = Nothing


Set OutApp = Nothing
End Sub

Send an email through Outlook using text from Word

Sub SendOutlookMessages()

'This macro will send an email through Outlook to a list of


'recipients whose emails are in excel. The body of the email comes
'from a word document which you will choose from your computer
'
Dim OL As Object, MailSendItem As Object
Dim W As Object
Dim MsgTxt As String, SendFile As String
Dim ToRangeCounter As Variant

SendFile = Application.GetOpenFilename(Title:="Select MS Word " & _


"file to mail, then click 'Open'", buttontext:="Send", _
MultiSelect:=False)
Set W = GetObject(SendFile)
MsgTxt = W.Range(Start:=W.Paragraphs(1).Range.Start, _
End:=W.Paragraphs(W.Paragraphs.Count).Range.End)
Set W = Nothing

Set OL = CreateObject("Outlook.Application")
Set MailSendItem = OL.CreateItem(olMailItem)
ToRangeCounter = 0

For Each xCell In ActiveSheet.Range(Range("tolist"), _


Range("tolist").End(xlDown))
ToRangeCounter = ToRangeCounter + 1
Next xCell

If ToRangeCounter = 256 Then ToRangeCounter = 1

With MailSendItem
.Subject = ActiveSheet.Range("subjectcell").Text
.Body = MsgTxt

For Each xRecipient In Range("tolist").Resize(ToRangeCounter, 1)


RecipientList = RecipientList & ";" & xRecipient
Next xRecipient

.To = RecipientList
.Send
End With

Set OL = Nothing

End Sub

Get Source Data from a Chart

Sub GetChartValues()

'This macro will retrieve the source data from a chart in excel
'This works for charts where the source data has been lost or
'damaged.
'Simply select the chart and run the macro - make sure to create a
'separate worksheet titled "ChartData" first though.
'
Dim NumberOfRows As Integer
Dim X As Object
Counter = 2
NumberOfRows = UBound(ActiveChart.SeriesCollection(1).Values)
Worksheets("ChartData").Cells(1, 1) = "X Values"
With Worksheets("ChartData")
.Range(.Cells(2, 1), _
.Cells(NumberOfRows + 1, 1)) = _
Application.Transpose(ActiveChart.SeriesCollection(1).XValues)
End With
For Each X In ActiveChart.SeriesCollection
Worksheets("ChartData").Cells(1, Counter) = X.Name
With Worksheets("ChartData")
.Range(.Cells(2, Counter), _
.Cells(NumberOfRows + 1, Counter)) = _
Application.Transpose(X.Values)
End With
Counter = Counter + 1
Next
End Sub

Excel Macro to Delete All Chart Sheets in Excel - Only Chart Sheets
are Deleted - Not Embedded Charts

Sub delete_all_chart_sheets_in_workbook()
'This example deletes every chart sheet in the active workbook.

ActiveWorkbook.Charts.Delete

End Sub

Excel Macro to Create a Line Chart

Sub Create_Line_Chart()
'create a line chart in excel with this macro

ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$A$1:$B$67")
ActiveChart.ChartType = xlLine

End Sub

Excel Macro to Create a Bar Chart

Sub Create_Bar_Chart()
'create a bar chart in excel with this macro

ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$A$1:$B$67")
ActiveChart.ChartType = xlBarClustered

End Sub

Excel Macro to Create a Column Chart

Sub Create_Column_Chart()
'create a column chart with this excel macro

ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$A$1:$B$67")
ActiveChart.ChartType = xlColumnClustered
End Sub

Excel Macro to Format Cells as an Accounting Number in Excel


Number Formatting

Sub Format_Cell_Accounting()

Selection.NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??


_);_(@_)"

End Sub

Macro to Format Cells as a Currency in Excel Number Formatting

Sub Format_Cell_Currency_US_Dollar()

Selection.NumberFormat = "$#,##0.00"

End Sub

Macro to Format Cells in The Long Date Format in Excel

Sub Format_Cell_Date_Long()

Selection.NumberFormat = "[$-F800]dddd, mmmm dd, yyyy"

End Sub

Macro to Format Cells in The Short Date Number Format in Excel

Sub Format_Cell_Date_Short()

Selection.NumberFormat = "m/d/yyyy"

End Sub

Excel Macro to Format Cells as a Fraction in Excel Number


Formatting

Sub Format_Cell_Fraction()

Selection.NumberFormat = "# ?/?"

End Sub

Excel Macro to Format Cells in The General (default) Format in


Excel Number Formatting
Sub Format_Cell_General()

Selection.NumberFormat = "General"

End Sub

Excel Macro to Format Cells in The Number (Numerical) Number


Format in Excel

Sub Format_Cell_Number()

Selection.NumberFormat = "0.00"

End Sub

Excel Macro to Format Cells as a Percentage in Excel Number


Formatting

Sub Format_Cell_Percentage()

Selection.NumberFormat = "0.00%"

End Sub

Excel Macro to Format Cells as a Scientific Number in Excel


Number Formatting

Sub Format_Cell_Scientific()

Selection.NumberFormat = "0.00E+00"

End Sub

Excel Macro to Format Cells as Text in Excel

Sub Format_Cell_Text()

Selection.NumberFormat = "@"

End Sub

Excel Macro to Format Cells as Time in Excel

Sub Format_Cell_Time()

Selection.NumberFormat = "[$-F400]h:mm:ss AM/PM"

End Sub
Excel Macro to Highlight Every Other Row in a Selection in Excel -
Table Formatting

Sub Highlight_Every_Other_Row()
'This macro highlights every other row within a selection of rows - you
select the table/rows you want formatted
Dim r As Integer

For r = 1 To Selection.Rows.Count

If r Mod 2 = 1 Then
Selection.Rows(r).Interior.ColorIndex = 37
End If

Next

End Sub

Excel Data Validation Macro that Adds a Drop Down Menu to a


Specific Cell in Excel

Sub Add_Drop_Down_Menu_Cell()

With Range("A1").Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop,
Operator:=xlBetween, _
Formula1:="=$D$1:$D$3"
.IgnoreBlank = True
.InCellDropdown = True
End With

End Sub

Excel Data Validation Macro that Adds a Drop Down Menu to a


Selected Cell in Excel
Sub Add_Drop_Down_Menu_Selection()

With Selection.Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop,
Operator:=xlBetween, _
Formula1:="=$D$1:$D$3"
.IgnoreBlank = True
.InCellDropdown = True
End With

End Sub
Free Excel Macro to Add an Input Message to a Specified Cell in
Excel

Sub Add_Cell_Input_Message_Cell()

With Range("A1").Validation
.Add Type:=xlValidateInputOnly
.InputTitle = "Message Title Goes Here"
.InputMessage = "Message Contents Go Here"
End With

End Sub

Free Excel Macro to Add an Input Message to a Selected Cell in


Excel
Sub Add_Cell_Input_Message_Selection()

With Selection.Validation
.Add Type:=xlValidateInputOnly
.InputTitle = "Message Title Goes Here"
.InputMessage = "Message Contents Go Here"
End With

End Sub

Excel Macro to Remove All Data Validation from a Specific Cell or


Range of Cells in Excel

Sub Remove_Data_Validation_Cell()

Range("A1").Validation.Delete

End Sub

Excel Macro to Remove All Data Validation from a Selection of


Cells in Excel
Sub Remove_Data_Validation_Selection()

Selection.Validation.Delete

End Sub
UDF to Count The Number of Words in a Cell or Range of Cells in
Excel

Function COUNTWORDS(rRange As Range) As Long

Dim rCell As Range


Dim Count As Long

For Each rCell In rRange

lCount = lCount + Len(Trim(rCell)) - Len(Replace(Trim(rCell), " ", ""))


+ 1

Next rCell

COUNTWORDS = lCount

End Function

UDF to Count The Number of Words in a Cell or Range of Cells in


Excel - With User-Specified Delimiter / Separator

Function COUNTWORDSC(rRange As Range, Optional separator As


Variant) As Long

Dim rCell As Range


Dim Count As Long

If IsMissing(separator) Then
separator = " "
End If

For Each rCell In rRange

lCount = lCount + Len(Trim(rCell)) - Len(Replace(Trim(rCell),


separator, "")) + 1

Next rCell

COUNTWORDSC = lCount

End Function

UDF to Calculate the Future Value (FV) of Compound Interest in


Excel

Function FVCOMPOUNDINTEREST(PV As Double, r As Double, N As


Double) As Double

FVCOMPOUNDINTEREST = PV * (1 + r) ^ N
End Function

UDF to Extract a Word from a Sentence / Cell in Excel - Allows for a


User-Defined Delimiter

Function GETTEXT(Text As Variant, N As Integer, Optional Delimiter


As Variant) As String

If IsMissing(Delimiter) Then
Delimiter = " "
End If

GETTEXT = Split(Text, Delimiter)(N - 1)

End Function

UDF to Generate a Non-Repeating List of Random Numbers in


Excel

Function RANDNUMNOREP(Bottom As Integer, Top As Integer, Amount As


Integer) As String
'This UDF will generate a non-repeating set of random numbers in excel
and display those in the same cell as the function

Dim iArr As Variant


Dim i As Integer
Dim r As Integer
Dim temp As Integer

Application.Volatile

ReDim iArr(Bottom To Top)

For i = Bottom To Top

iArr(i) = i

Next i

For i = Top To Bottom + 1 Step -1

r = Int(Rnd() * (i - Bottom + 1)) + Bottom

temp = iArr(r)

iArr(r) = iArr(i)

iArr(i) = temp

Next i
For i = Bottom To Bottom + Amount - 1

RANDNUMNOREP = RANDNUMNOREP & " " & iArr(i)

Next i

RANDNUMNOREP = Trim(RANDNUMNOREP)

End Function

UDF to Display The Actual Link / Email Address From Links in


Excel

Function SHOWLINK(cell As Range, Optional Default As Variant)


'This UDF will display all links as text and display the full http
address that is in the hyperlink
'This UDF also automatically detects if the link is an Email address
and displays it correctly

If (cell.Range("A1").Hyperlinks.Count <> 1) Then

If IsMissing(Default) Then
SHOWLINK = "Not a Link"
Else
SHOWLINK = Default
End If

Else

If Left(cell.Range("A1").Hyperlinks(1).Address, 7) = "mailto:" Then


SHOWLINK = Right(cell.Range("A1").Hyperlinks(1).Address,
Len(cell.Range("A1").Hyperlinks(1).Address) - 7)
Else
SHOWLINK = cell.Range("A1").Hyperlinks(1).Address
End If

End If

End Function

UDF to Perform a Vlookup That Searches The Entire Workbook -


All Worksheets in The Workbook

Function VLOOKUPWORKBOOK(Look_Value As Variant, Tble_Array As


Range, Col_num As Integer, Optional Range_look As Boolean)
'Vlookup function that will search all worksheets in the workbook -
however, the data table that is being searched must be in the same
'location on every worksheet.

Dim wSheet As Worksheet


Dim vFound
On Error Resume Next

For Each wSheet In ActiveWorkbook.Worksheets

With wSheet

Set Tble_Array = .Range(Tble_Array.Address)

vFound = WorksheetFunction.VLookup(Look_Value, Tble_Array, Col_num,


Range_look)

End With

If Not IsEmpty(vFound) Then Exit For

Next wSheet

Set Tble_Array = Nothing

VLOOKUPWORKBOOK = vFound

End Function

WEEKNUM UDF for Excel Versions That Don't Contain This


Function

Function WEEKNUMUDF(D As Date, FWDayArg As Integer) As Integer

WEEKNUMUDF = CInt(Format(D, "ww", FWDayArg))

End Function

UDF to Return the ISO Week Number from a Date in Excel

Function ISOWEEKNUMBER(InDate As Date) As Long


Dim D As Date

D = DateSerial(Year(InDate - WeekDay(InDate - 1) + 4), 1, 3)

ISOWEEKNUMBER = Int((InDate - D + WeekDay(D) + 5) / 7)

End Function

UDF to Return the ISO Standards Start of the Year in Excel - First
Monday of the Year

Function ISOYEARSTART(Year As Integer) As Date


Dim WeekDay As Integer
Dim NewYear As Date
NewYear = DateSerial(Year, 1, 1)
WeekDay = (NewYear - 2) Mod 7

If WeekDay < 4 Then


ISOYEARSTART = NewYear - WeekDay
Else
ISOYEARSTART = NewYear - WeekDay + 7
End If

End Function

UDF to Convert Numeric Dollar Values into Text in Excel

Option Explicit
'Main Function
Function SPELLDOLLAMNT(ByVal MyNumber)
Dim Dollars, Cents, Temp
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert cents and set MyNumber to dollar amount.
If DecimalPlace > 0 Then
Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
"00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1
Loop
Select Case Dollars
Case ""
Dollars = "No Dollars"
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars & " Dollars"
End Select
Select Case Cents
Case ""
Cents = " and No Cents"
Case "One"
Cents = " and One Cent"
Case Else
Cents = " and " & Cents & " Cents"
End Select
SPELLDOLLAMNT = Dollars & Cents
End Function

' Converts a number from 100-999 into text


Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
Result = Result & GetTens(Mid(MyNumber, 2))
Else
Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function

' Converts a number from 10 to 99 into text.


Function GetTens(TensText)
Dim Result As String
Result = "" ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then ' If value between 10-19...
Select Case Val(TensText)
Case 10: Result = "Ten"
Case 11: Result = "Eleven"
Case 12: Result = "Twelve"
Case 13: Result = "Thirteen"
Case 14: Result = "Fourteen"
Case 15: Result = "Fifteen"
Case 16: Result = "Sixteen"
Case 17: Result = "Seventeen"
Case 18: Result = "Eighteen"
Case 19: Result = "Nineteen"
Case Else
End Select
Else ' If value between 20-99...
Select Case Val(Left(TensText, 1))
Case 2: Result = "Twenty "
Case 3: Result = "Thirty "
Case 4: Result = "Forty "
Case 5: Result = "Fifty "
Case 6: Result = "Sixty "
Case 7: Result = "Seventy "
Case 8: Result = "Eighty "
Case 9: Result = "Ninety "
Case Else
End Select
Result = Result & GetDigit _
(Right(TensText, 1)) ' Retrieve ones place.
End If
GetTens = Result
End Function

' Converts a number from 1 to 9 into text.


Function GetDigit(Digit)
Select Case Val(Digit)
Case 1: GetDigit = "One"
Case 2: GetDigit = "Two"
Case 3: GetDigit = "Three"
Case 4: GetDigit = "Four"
Case 5: GetDigit = "Five"
Case 6: GetDigit = "Six"
Case 7: GetDigit = "Seven"
Case 8: GetDigit = "Eight"
Case 9: GetDigit = "Nine"
Case Else: GetDigit = ""
End Select
End Function

UDF to Output the Worksheet Name in a Cell in Excel

Function SHEETNAME()

SHEETNAME = Range("A1").Parent.Name

End Function

UDF to Output the Name of the Current Excel Workbook Including


Extension

Function NAMEWORKBOOKEXT() As String

NAMEWORKBOOKEXT = ThisWorkbook.Name

End Function

UDF to Output the File Path to and Name of a Workbook in Excel

Function NAMEWBKFILEPATH() As String

NAMEWBKFILEPATH = ThisWorkbook.FullName

End Function

UDF to Output the Name of the Current Excel Workbook Without


the File Extension

Function NAMEWORKBOOK() As String


NAMEWORKBOOK = Left(ThisWorkbook.Name, InStr(1, ThisWorkbook.Name, ".",
vbTextCompare) - 1)

End Function

UDF to Determine a Cell's Color and Output that Color as Text or


an Index Number in Excel

Function CELLCOLOR(rCell As Range, Optional ColorName As Boolean)

Dim strColor As String


Dim iIndexNum As Integer

Select Case rCell.Interior.ColorIndex

Case 1

strColor = "Black"

iIndexNum = 1

Case 53

strColor = "Brown"

iIndexNum = 53

Case 52

strColor = "Olive Green"

iIndexNum = 52

Case 51

strColor = "Dark Green"

iIndexNum = 51

Case 49

strColor = "Dark Teal"

iIndexNum = 49

Case 11

strColor = "Dark Blue"

iIndexNum = 11
Case 55

strColor = "Indigo"

iIndexNum = 55

Case 56

strColor = "Gray-80%"

iIndexNum = 56

Case 9

strColor = "Dark Red"

iIndexNum = 9

Case 46

strColor = "Orange"

iIndexNum = 46

Case 12

strColor = "Dark Yellow"

iIndexNum = 12

Case 10

strColor = "Green"

iIndexNum = 10

Case 14

strColor = "Teal"

iIndexNum = 14

Case 5

strColor = "Blue"

iIndexNum = 5

Case 47

strColor = "Blue-Gray"
iIndexNum = 47

Case 16

strColor = "Gray-50%"

iIndexNum = 16

Case 3

strColor = "Red"

iIndexNum = 3

Case 45

strColor = "Light Orange"

iIndexNum = 45

Case 43

strColor = "Lime"

iIndexNum = 43

Case 50

strColor = "Sea Green"

iIndexNum = 50

Case 42

strColor = "Aqua"

iIndexNum = 42

Case 41

strColor = "Light Blue"

iIndexNum = 41

Case 13

strColor = "Violet"

iIndexNum = 13

Case 48
strColor = "Gray-40%"

iIndexNum = 48

Case 7

strColor = "Pink"

iIndexNum = 7

Case 44

strColor = "Gold"

iIndexNum = 44

Case 6

strColor = "Yellow"

iIndexNum = 6

Case 4

strColor = "Bright Green"

iIndexNum = 4

Case 8

strColor = "Turqoise"

iIndexNum = 8

Case 33

strColor = "Sky Blue"

iIndexNum = 33

Case 54

strColor = "Plum"

iIndexNum = 54

Case 15

strColor = "Gray-25%"

iIndexNum = 15
Case 38

strColor = "Rose"

iIndexNum = 38

Case 40

strColor = "Tan"

iIndexNum = 40

Case 36

strColor = "Light Yellow"

iIndexNum = 36

Case 35

strColor = "Light Green"

iIndexNum = 35

Case 34

strColor = "Light Turqoise"

iIndexNum = 34

Case 37

strColor = "Pale Blue"

iIndexNum = 37

Case 39

strColor = "Lavendar"

iIndexNum = 39

Case 2

strColor = "White"

iIndexNum = 2

Case Else

strColor = "Custom color or no fill"


End Select

If ColorName = False Or strColor = "Custom color or no fill" Then

CELLCOLOR = strColor

Else

CELLCOLOR = iIndexNum

End If

End Function

UDF to Get Text from Comments in Excel Including the Author of


the Comment

Function GETCOMMTEXTWITHAUTH(rCommentCell As Range)

Dim cmnt As String

On Error Resume Next

cmnt = WorksheetFunction.Clean(rCommentCell.Comment.Text)

GETCOMMTEXTWITHAUTH = cmnt

On Error GoTo 0

End Function

UDF to Get Comment Text from Cell Comments in Excel

Function GETCOMMTEXT(rCommentCell As Range)

Dim cmnt As String

On Error Resume Next

cmnt = WorksheetFunction.Clean(rCommentCell.Comment.Text)

GETCOMMTEXT = Right(cmnt, Len(cmnt) - InStr(1, cmnt, ":",


vbTextCompare))

On Error GoTo 0
End Function

Open a PowerPoint Presentation from Excel

Sub Open_PowerPoint_Presentation()

'Opens a PowerPoint Document from Excel

Dim objPPT As Object

Set objPPT = CreateObject("PowerPoint.Application")


objPPT.Visible = True

'Change the directory path and file name to the location


'of your document

objPPT.Presentations.Open "C:\test.ppt"

End Sub

Convert Text in Cells to Proper Case - First Letter of Each Word


Capitalized

Sub Proper_Case()

'
'This will make the first letter of the text within any selection of
'cells uppercase.
'
For Each x In Selection
x.Value = Application.Proper(x.Value)
Next
End Sub

Protect All Worksheets at Once

Sub Protect_All()

For i = 1 To Sheets.Count
Sheets(i).Protect
Next i

End Sub

Вам также может понравиться