0% found this document useful (0 votes)
2 views

vba

The document contains a series of VBA functions designed for various data manipulation tasks in Excel. These functions include retrieving the last word from a cell, reversing strings, finding the nth largest number, counting word occurrences, converting numbers to words, and more. Each function is defined with its purpose and includes the necessary code to perform its task.

Uploaded by

Pvinkal Singh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

vba

The document contains a series of VBA functions designed for various data manipulation tasks in Excel. These functions include retrieving the last word from a cell, reversing strings, finding the nth largest number, counting word occurrences, converting numbers to words, and more. Each function is defined with its purpose and includes the necessary code to perform its task.

Uploaded by

Pvinkal Singh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

' Function Name: LastWord

' Purpose: Returns the last word from the given cell.

' Function Name: ReverseString


' Purpose: Reverses the input string.

' Function Name: NthLargest


' Purpose: Finds the nth largest number in a specified range.

' Function Name: CountWord


' Purpose: Counts occurrences of a specified word in a range.

' Function Name: NumberToWords


' Purpose: Converts a number into its English words representation (e.g., "123" to
"One Hundred Twenty-Three Dollars").

' Function Name: MaxUnique


' Purpose: Returns the maximum unique numeric value from a range.

' Function Name: FirstNonEmpty


' Purpose: Finds and returns the first non-empty value in a specified range.

' Function Name: ListDuplicatesWithCounts


' Purpose: Lists duplicate values in a range along with their counts.

' Function Name: ListDuplicates


' Purpose: Lists duplicate values in a range without counts.

' Function Name: SumByColor


' Purpose: Sums values in a range that have a specified background color.

' Function Name: LookupAllValues


' Purpose: Finds all occurrences of a lookup value in a range and returns
corresponding values from another range.

' Function Name: Levenshtein


' Purpose: Calculates the Levenshtein distance between two strings (number of edits
needed to transform one string into another).

' Function Name: FuzzyLookup


' Purpose: Performs a fuzzy lookup, returning values from a range that match a
lookup value within a specified similarity threshold.

Function LastWord(cell As Range) As String


Dim words() As String
words = Split(cell.Value, " ")
LastWord = words(UBound(words))
End Function
Function ReverseString(txt As String) As String
Dim i As Integer
Dim result As String

For i = Len(txt) To 1 Step -1


result = result & Mid(txt, i, 1)
Next i
ReverseString = result
End Function
Function NthLargest(rng As Range, n As Integer) As Double
Dim arr() As Double
Dim i As Long, j As Long, Temp As Double

' Load values into an array


ReDim arr(1 To rng.Count)
i = 1
For Each cell In rng
If IsNumeric(cell.Value) Then
arr(i) = cell.Value
i = i + 1
End If
Next cell
ReDim Preserve arr(1 To i - 1)

' Sort the array


For i = LBound(arr) To UBound(arr) - 1
For j = i + 1 To UBound(arr)
If arr(i) < arr(j) Then
Temp = arr(i)
arr(i) = arr(j)
arr(j) = Temp
End If
Next j
Next i

' Return the nth largest value


NthLargest = arr(n)
End Function
Function CountWord(rng As Range, word As String) As Integer
Dim cell As Range
Dim Count As Integer

For Each cell In rng


Count = Count + (Len(cell.Value) - Len(Replace(cell.Value, word, ""))) /
Len(word)
Next cell

CountWord = Count
End Function
Function NumberToWords(ByVal MyNumber)
Dim Units As String
Dim Tens As String
Dim Hundreds As String
Dim DecimalPlace As Integer, Count As Integer
Dim Temp As String
Dim DecimalPart As String

ReDim Place(9) As String


Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "

MyNumber = Trim(CStr(MyNumber))
DecimalPlace = InStr(MyNumber, ".")
If DecimalPlace > 0 Then
DecimalPart = Mid(MyNumber, DecimalPlace + 1)
MyNumber = Left(MyNumber, DecimalPlace - 1)
End If

Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Units = Temp & Place(Count) & Units
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1
Loop

NumberToWords = Application.Trim(Units) & " Dollars and " & DecimalPart & "
Cents"
End Function

Function GetHundreds(ByVal MyNumber)


Dim result As String
If Val(MyNumber) = 0 Then Exit Function

MyNumber = Right("000" & MyNumber, 3)

If Mid(MyNumber, 1, 1) <> "0" Then


result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
End If

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

Function GetTens(TensText)
Dim result As String
result = ""
If Val(Left(TensText, 1)) = 1 Then
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
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))
End If

GetTens = result
End Function

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
Function MaxUnique(rng As Range) As Double
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

Dim cell As Range


For Each cell In rng
If IsNumeric(cell.Value) And Not dict.exists(cell.Value) Then
dict.Add cell.Value, cell.Value
End If
Next cell

MaxUnique = WorksheetFunction.Max(dict.items)
End Function
Function FirstNonEmpty(rng As Range) As Variant
Dim cell As Range
For Each cell In rng
If cell.Value <> "" Then
FirstNonEmpty = cell.Value
Exit Function
End If
Next cell
FirstNonEmpty = "All empty"
End Function
Function ListDuplicatesWithCounts(rng As Range) As String
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

Dim cell As Range


Dim duplicates As String
duplicates = ""
' First, count occurrences of each value
For Each cell In rng
If Not IsEmpty(cell.Value) Then
If dict.exists(cell.Value) Then
dict(cell.Value) = dict(cell.Value) + 1
Else
dict.Add cell.Value, 1
End If
End If
Next cell

' Now, gather duplicates and their counts


For Each Key In dict.keys
If dict(Key) > 1 Then
duplicates = duplicates & Key & " (Count: " & dict(Key) & "), "
End If
Next Key

' Remove trailing comma and space


If Len(duplicates) > 0 Then
duplicates = Left(duplicates, Len(duplicates) - 2)
End If

ListDuplicatesWithCounts = duplicates
End Function

Function ListDuplicates(rng As Range) As String


Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

Dim cell As Range


Dim duplicates As String
duplicates = ""

' First, count occurrences of each value


For Each cell In rng
If Not IsEmpty(cell.Value) Then
If dict.exists(cell.Value) Then
dict(cell.Value) = dict(cell.Value) + 1
Else
dict.Add cell.Value, 1
End If
End If
Next cell

' Now, gather duplicates


For Each Key In dict.keys
If dict(Key) > 1 Then
duplicates = duplicates & Key & ", "
End If
Next Key

' Remove trailing comma and space


If Len(duplicates) > 0 Then
duplicates = Left(duplicates, Len(duplicates) - 2)
End If

ListDuplicates = duplicates
End Function
Function SumByColor(rng As Range, colorCell As Range) As Double
Dim cell As Range
Dim total As Double
Dim targetColor As Long

' Get the color of the cell to match


targetColor = colorCell.Interior.Color

total = 0

' Loop through each cell in the specified range


For Each cell In rng
' Check if the cell color matches the target color
If cell.Interior.Color = targetColor Then
total = total + cell.Value
End If
Next cell

SumByColor = total
End Function
Function LookupAllValues(lookupValue As String, lookupRange As Range, returnRange
As Range) As String
Dim i As Long
Dim cellValue As String
Dim result As String
Dim regex As Object

' Initialize result to an empty string


result = ""

' Create a regular expression object


Set regex = CreateObject("VBScript.RegExp")
regex.Global = True
regex.IgnoreCase = True
regex.Pattern = "\b" & Replace(lookupValue, " ", "") & "\b" ' Match the
lookupValue as a whole word

' Loop through each cell in the lookup range


For i = 1 To lookupRange.Rows.Count
' Clean the cell value by removing special characters and converting to a
consistent format
cellValue = Application.WorksheetFunction.Trim( _
Application.WorksheetFunction.Substitute( _
Application.WorksheetFunction.Substitute( _
Application.WorksheetFunction.Substitute( _
Application.WorksheetFunction.Substitute( _
Application.WorksheetFunction.Substitute( _
Application.WorksheetFunction.Substitute( _
lookupRange.Cells(i, 1).Value, ",", " "), _
".", " "), _
"!", " "), _
"?", " "), _
";", " "), _
":", " "))

' Check if the lookup value is found in the cleaned cell value
If regex.Test(cellValue) Then
' If found, concatenate the corresponding value from the return range
result = result & Trim(returnRange.Cells(i, 1).Value) & ", "
End If
Next i

' Remove the trailing comma and space if results were found
If Len(result) > 0 Then
result = Left(result, Len(result) - 2)
Else
result = "Not Found"
End If

LookupAllValues = result
End Function

Function Levenshtein(s1 As String, s2 As String) As Long


Dim i As Long, j As Long
Dim cost As Long
Dim d() As Long

ReDim d(0 To Len(s1), 0 To Len(s2))

For i = 0 To Len(s1)
d(i, 0) = i
Next i

For j = 0 To Len(s2)
d(0, j) = j
Next j

For i = 1 To Len(s1)
For j = 1 To Len(s2)
If Mid(s1, i, 1) = Mid(s2, j, 1) Then
cost = 0
Else
cost = 1
End If

d(i, j) = Application.Min(d(i - 1, j) + 1, _
d(i, j - 1) + 1, _
d(i - 1, j - 1) + cost)
Next j
Next i

Levenshtein = d(Len(s1), Len(s2))


End Function
Function FuzzyLookup(lookupValue As String, lookupRange As Range, returnRange As
Range) As String
Dim i As Long
Dim result As String
Dim distance As Long
Dim threshold As Long
Dim matchCount As Long

' Prompt user for the desired percentage only if it has not been set yet
If IsEmpty(similarityThreshold) Then
similarityThreshold = Application.InputBox("Enter the desired similarity
percentage (0-100):", "Similarity Percentage", 80, Type:=1)

' Validate input


If similarityThreshold < 0 Or similarityThreshold > 100 Then
FuzzyLookup = "Invalid percentage. Please enter a value between 0 and
100."
Exit Function
End If
End If

' Set the threshold based on the stored percentage


threshold = Len(lookupValue) * (1 - similarityThreshold / 100) ' Allowable
distance

' Initialize result


result = ""
matchCount = 0

' Loop through each cell in the lookup range


For i = 1 To lookupRange.Rows.Count
distance = Levenshtein(Application.Trim(lookupRange.Cells(i, 1).Value),
Application.Trim(lookupValue))

' If the distance is less than or equal to the threshold, consider it a


match
If distance <= threshold Then
result = result & Trim(returnRange.Cells(i, 1).Value) & ", "
matchCount = matchCount + 1
End If
Next i

' Remove the trailing comma and space if results were found
If matchCount > 0 Then
result = Left(result, Len(result) - 2)
Else
result = "Not Found"
End If

FuzzyLookup = result
End Function

Function SeparateWordsAndNumbers(cell As Range) As Variant


Dim txt As String
Dim words As Collection
Dim numbers As Collection
Dim i As Integer
Dim result(1) As Variant ' Array to hold words and numbers

Set words = New Collection


Set numbers = New Collection

txt = cell.Value

' Loop through each character in the cell value


Dim currentWord As String
currentWord = ""

For i = 1 To Len(txt)
Dim currentChar As String
currentChar = Mid(txt, i, 1)

If currentChar Like "[A-Za-z]" Then


currentWord = currentWord & currentChar
ElseIf currentChar Like "[0-9.]" Then
' Handle numeric characters and decimals
If currentWord <> "" Then
words.Add currentWord
currentWord = ""
End If
currentWord = currentWord & currentChar
ElseIf currentChar = " " Then
If currentWord <> "" Then
If IsNumeric(currentWord) Then
numbers.Add currentWord
Else
words.Add currentWord
End If
currentWord = ""
End If
End If
Next i

' Check for the last word or number


If currentWord <> "" Then
If IsNumeric(currentWord) Then
numbers.Add currentWord
Else
words.Add currentWord
End If
End If

' Assign collections to the result array


result(0) = Join(CollectionToArray(words), ", ")
result(1) = Join(CollectionToArray(numbers), ", ")

SeparateWordsAndNumbers = result
End Function

' Helper function to convert a collection to an array


Function CollectionToArray(coll As Collection) As Variant
Dim arr() As Variant
Dim i As Integer
ReDim arr(0 To coll.Count - 1)

For i = 1 To coll.Count
arr(i - 1) = coll(i)
Next i

CollectionToArray = arr
End Function

Function ExtractText(ByVal inputString As String) As String


Dim i As Integer
Dim textPart As String

' Loop through each character in the input string


For i = 1 To Len(inputString)
' Check if the character is not a number
If Not IsNumeric(Mid(inputString, i, 1)) Then
textPart = textPart & Mid(inputString, i, 1) ' Concatenate text
End If
Next i

ExtractText = textPart ' Return the extracted text


End Function

Function ExtractNumbers(ByVal inputString As String) As String


Dim i As Integer
Dim numberPart As String

' Loop through each character in the input string


For i = 1 To Len(inputString)
' Check if the character is a number
If IsNumeric(Mid(inputString, i, 1)) Then
numberPart = numberPart & Mid(inputString, i, 1) ' Concatenate numbers
End If
Next i

ExtractNumbers = numberPart ' Return the extracted numbers


End Function
Function ExtractNumbersWithHyphen(ByVal inputString As String) As String
Dim i As Integer
Dim numberPart As String
Dim result As String
Dim numArray() As String
Dim numCount As Integer

' Loop through each character in the input string


For i = 1 To Len(inputString)
' Check if the character is a number
If IsNumeric(Mid(inputString, i, 1)) Then
' If the current character is a digit, keep adding it to numberPart
numberPart = numberPart & Mid(inputString, i, 1)
' If the next character is not a number, store the complete number
If i = Len(inputString) Or Not IsNumeric(Mid(inputString, i + 1, 1))
Then
numCount = numCount + 1
ReDim Preserve numArray(1 To numCount)
numArray(numCount) = numberPart
numberPart = "" ' Reset for the next number
End If
End If
Next i

' Join the numbers with hyphen


If numCount > 0 Then
result = Join(numArray, "-")
End If

ExtractNumbersWithHyphen = result ' Return the formatted numbers


End Function

Function CleanAndSpaceString(ByVal inputString As String) As String


Dim i As Integer
Dim cleanedString As String
Dim currentChar As String

' Loop through each character in the input string


For i = 1 To Len(inputString)
currentChar = Mid(inputString, i, 1)
' Check if the character is alphanumeric (letters or numbers)
If currentChar Like "[A-Za-z0-9]" Then
cleanedString = cleanedString & currentChar ' Append valid character
Else
' Append a space if the character is not alphanumeric
cleanedString = cleanedString & " "
End If
Next i

' Trim leading and trailing spaces and replace multiple spaces with a single
space
CleanAndSpaceString = Trim(Replace(cleanedString, " ", " "))
End Function

Function FindMatches(lookupValue As String, lookupRange As Range) As String


Dim cell As Range
Dim result As String

' Loop through each cell in the lookup range


For Each cell In lookupRange
' Check if the lookupValue is found within the cell's text
If InStr(1, cell.Value, lookupValue, vbTextCompare) > 0 Then
' If match is found, add it to the result string with a comma
result = result & cell.Value & ", "
End If
Next cell

' Remove the last comma and space if matches are found
If Len(result) > 0 Then
result = Left(result, Len(result) - 2)
Else
result = "No Match Found"
End If

' Return the result


FindMatches = result
End Function
Function FindFirstWordMatch(lookupValue As String, lookupRange As Range) As String
Dim firstWord As String
Dim cell As Range

' Extract the first word from the lookupValue


firstWord = Split(lookupValue, " ")(0)

' Loop through each cell in the lookup range


For Each cell In lookupRange
' Check if the first word is found within the cell's text
If InStr(1, cell.Value, firstWord, vbTextCompare) > 0 Then
' If a match is found, return the cell's value
FindFirstWordMatch = cell.Value
Exit Function
End If
Next cell

' If no match is found, return "No Match Found"


FindFirstWordMatch = "No Match Found"
End Function

You might also like