Make your Excel a powerful tool with below VB codes
Shortcut key for VB in Excel is Alt+F11 & for Macros Alt+F8
Convert Numbers into words
Function ConvertToIndianWords(ByVal MyNumber)
Dim Rupees As String, Paise As String
Dim DecimalPlace As Integer
Dim TempStr As String
Dim PaisePart As String
MyNumber = Trim(Str(MyNumber))
DecimalPlace = InStr(MyNumber, ".")
If DecimalPlace > 0 Then
PaisePart = Mid(MyNumber, DecimalPlace + 1)
MyNumber = Left(MyNumber, DecimalPlace - 1)
Else
PaisePart = ""
End If
TempStr = ConvertWholeNumberToWords(MyNumber)
If PaisePart <> "" Then
If Len(PaisePart) = 1 Then PaisePart = PaisePart & "0" ' e.g. .5 becomes .50
Paise = " and " & ConvertTens(PaisePart) & " Paise"
End If
ConvertToIndianWords = Application.Trim(TempStr & Paise)
End Function
Private Function ConvertWholeNumberToWords(ByVal num As String) As String
Dim words As String
Dim n As Double
n = Val(num)
If n = 0 Then
ConvertWholeNumberToWords = "Zero"
Exit Function
End If
words = ""
If n >= 10000000 Then
words = words & ConvertHundreds(Int(n / 10000000)) & " Crore "
n = n Mod 10000000
End If
If n >= 100000 Then
words = words & ConvertHundreds(Int(n / 100000)) & " Lakh "
n = n Mod 100000
End If
If n >= 1000 Then
words = words & ConvertHundreds(Int(n / 1000)) & " Thousand "
n = n Mod 1000
End If
If n >= 100 Then
words = words & ConvertHundreds(Int(n / 100)) & " Hundred "
n = n Mod 100
End If
If n > 0 Then
If words <> "" Then words = words & "and "
words = words & ConvertTens(n)
End If
ConvertWholeNumberToWords = Application.Trim(words)
End Function
Private Function ConvertHundreds(ByVal n As Integer) As String
Dim word As String
If n > 99 Then
word = GetDigit(Int(n / 100)) & " Hundred "
n = n Mod 100
End If
If n > 0 Then
word = word & ConvertTens(n)
End If
ConvertHundreds = word
End Function
Private Function ConvertTens(ByVal n As Variant) As String
Dim teensArray(9 To 19) As String
Dim tensArray(2 To 9) As String
Dim unitsArray(1 To 9) As String
teensArray(10) = "Ten": teensArray(11) = "Eleven": teensArray(12) = "Twelve"
teensArray(13) = "Thirteen": teensArray(14) = "Fourteen": teensArray(15) = "Fifteen"
teensArray(16) = "Sixteen": teensArray(17) = "Seventeen": teensArray(18) = "Eighteen": teensArray(19) = "Nineteen"
tensArray(2) = "Twenty": tensArray(3) = "Thirty": tensArray(4) = "Forty"
tensArray(5) = "Fifty": tensArray(6) = "Sixty": tensArray(7) = "Seventy"
tensArray(8) = "Eighty": tensArray(9) = "Ninety"
unitsArray(1) = "One": unitsArray(2) = "Two": unitsArray(3) = "Three"
unitsArray(4) = "Four": unitsArray(5) = "Five": unitsArray(6) = "Six"
unitsArray(7) = "Seven": unitsArray(8) = "Eight": unitsArray(9) = "Nine"
Dim t As Integer: t = Int(n)
Dim Result As String
If t = 0 Then
Result = ""
ElseIf t < 10 Then
Result = unitsArray(t)
ElseIf t >= 10 And t < 20 Then
Result = teensArray(t)
Else
Result = tensArray(Int(t / 10))
If t Mod 10 > 0 Then
Result = Result & " " & unitsArray(t Mod 10)
End If
End If
ConvertTens = Result
End Function
Private Function GetDigit(ByVal 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
Steps
1. Click on Copy the VB Code.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the Number column use ConverttoIndianword formula to convert the number into words.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the Number column use ConverttoIndianword formula to convert the number into words.
Extract Address in 100 charcter with City, State, pincode in separate cell
Sub ProcessAddresses()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(1)
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim cities As Variant
cities = Array("Mumbai", "Delhi", "Bangalore", "Hyderabad", "Ahmedabad", "Chennai", "Kolkata", "Surat", "Pune", "Jaipur", _
"Lucknow", "Kanpur", "Nagpur", "Indore", "Thane", "Bhopal", "Visakhapatnam", "Patna", "Vadodara", "Ghaziabad", _
"Ludhiana", "Agra", "Nashik", "Faridabad", "Meerut", "Rajkot", "Kalyan", "Vasai", "Varanasi", "Srinagar", _
"Aurangabad", "Dhanbad", "Amritsar", "Navi Mumbai", "Prayagraj", "Ranchi", "Howrah", "Coimbatore", "Jabalpur", "Gwalior")
Dim countries As Variant
countries = Array("India", "USA", "UK", "Canada", "Australia")
' State name and short code pairs
Dim stateData As Variant
stateData = Array( _
Array("Andhra Pradesh", "AP"), Array("Arunachal Pradesh", "AR"), Array("Assam", "AS"), _
Array("Bihar", "BR"), Array("Chhattisgarh", "CG"), Array("Goa", "GA"), _
Array("Gujarat", "GJ"), Array("Haryana", "HR"), Array("Himachal Pradesh", "HP"), _
Array("Jharkhand", "JH"), Array("Karnataka", "KA"), Array("Kerala", "KL"), _
Array("Madhya Pradesh", "MP"), Array("Maharashtra", "MH"), Array("Manipur", "MN"), _
Array("Meghalaya", "ML"), Array("Mizoram", "MZ"), Array("Nagaland", "NL"), _
Array("Odisha", "OD"), Array("Punjab", "PB"), Array("Rajasthan", "RJ"), _
Array("Sikkim", "SK"), Array("Tamil Nadu", "TN"), Array("Telangana", "TS"), _
Array("Tripura", "TR"), Array("Uttar Pradesh", "UP"), Array("Uttarakhand", "UK"), _
Array("West Bengal", "WB") _
)
Dim i As Long
For i = 2 To lastRow
Dim fullAddress As String
fullAddress = Trim(ws.Cells(i, "A").Value)
If fullAddress = "" Then GoTo NextRow
' Remove duplicate words
Dim words() As String
Dim uniqueWords As Object: Set uniqueWords = CreateObject("Scripting.Dictionary")
words = Split(fullAddress, " ")
Dim cleanedAddress As String: cleanedAddress = ""
Dim w As Variant
For Each w In words
If Not uniqueWords.exists(LCase(w)) Then
uniqueWords.Add LCase(w), w
cleanedAddress = cleanedAddress & w & " "
End If
Next w
cleanedAddress = Trim(cleanedAddress)
' Extract and remove pincode
Dim pincode As String
pincode = ExtractPincode(cleanedAddress)
If pincode <> "" Then
ws.Cells(i, "I").Value = pincode
cleanedAddress = Replace(cleanedAddress, pincode, "", , , vbTextCompare)
End If
' Extract and remove state (full name or short code)
Dim state As String
state = ExtractState(cleanedAddress, stateData)
If state <> "" Then
ws.Cells(i, "G").Value = state
ws.Cells(i, "J").Value = GetStateShortCode(state, stateData)
cleanedAddress = Replace(cleanedAddress, state, "", , , vbTextCompare)
cleanedAddress = Replace(cleanedAddress, GetStateShortCode(state, stateData), "", , , vbTextCompare)
End If
' Extract and remove country
Dim country As String
country = ExtractComponent(cleanedAddress, countries)
If country <> "" Then
ws.Cells(i, "H").Value = country
cleanedAddress = Replace(cleanedAddress, country, "", , , vbTextCompare)
End If
' Extract and remove city
Dim city As String
city = ExtractComponent(cleanedAddress, cities)
If city <> "" Then
ws.Cells(i, "F").Value = city
cleanedAddress = Replace(cleanedAddress, city, "", , , vbTextCompare)
End If
cleanedAddress = Application.WorksheetFunction.Trim(cleanedAddress)
' Split cleanedAddress into 100-character chunks (B to E)
Dim tokens() As String
tokens = Split(cleanedAddress, " ")
Dim chunk As String: chunk = ""
Dim colOffset As Integer: colOffset = 1 ' Start at column B
Dim j As Long
For j = LBound(tokens) To UBound(tokens)
If Len(chunk & " " & tokens(j)) <= 100 Then
chunk = chunk & " " & tokens(j)
Else
ws.Cells(i, colOffset + 1).Value = Trim(chunk)
colOffset = colOffset + 1
If colOffset > 4 Then Exit For
chunk = tokens(j)
End If
Next j
If chunk <> "" And colOffset <= 4 Then
ws.Cells(i, colOffset + 1).Value = Trim(chunk)
End If
NextRow:
Next i
MsgBox "Address processing complete."
End Sub
Function ExtractPincode(text As String) As String
Dim re As Object: Set re = CreateObject("VBScript.RegExp")
re.Pattern = "\b\d{5,6}\b"
re.Global = False
re.IgnoreCase = True
Dim matches As Object
Set matches = re.Execute(text)
If matches.Count > 0 Then
ExtractPincode = matches(0)
Else
ExtractPincode = ""
End If
End Function
Function ExtractComponent(text As String, list As Variant) As String
Dim item As Variant
For Each item In list
If InStr(1, text, item, vbTextCompare) > 0 Then
ExtractComponent = item
Exit Function
End If
Next item
ExtractComponent = ""
End Function
Function ExtractState(text As String, stateData As Variant) As String
Dim i As Long
For i = LBound(stateData) To UBound(stateData)
If InStr(1, text, stateData(i)(0), vbTextCompare) > 0 Then
ExtractState = stateData(i)(0)
Exit Function
ElseIf InStr(1, text, " " & stateData(i)(1) & " ", vbTextCompare) > 0 Or _
Right(LCase(text), 3) = " " & LCase(stateData(i)(1)) Then
ExtractState = stateData(i)(0)
Exit Function
End If
Next i
ExtractState = ""
End Function
Function GetStateShortCode(state As String, stateData As Variant) As String
Dim i As Long
For i = LBound(stateData) To UBound(stateData)
If StrComp(state, stateData(i)(0), vbTextCompare) = 0 Then
GetStateShortCode = stateData(i)(1)
Exit Function
End If
Next i
GetStateShortCode = ""
End Function
Steps
1. Click on Copy the VB Code.
2. Click Ok on the alert message.
3. Open the excel file where extraction need to be done.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. Type Alt+F8 for macors and click on run.
2. Click Ok on the alert message.
3. Open the excel file where extraction need to be done.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. Type Alt+F8 for macors and click on run.
Convert Words into Number
Function ConvertIndianWordsToNumber(ByVal Words As String) As Double
Dim WordList() As String
Dim i As Long
Dim Num As Double
Dim Temp As Double
Dim CurrentWord As String
Dim Multipliers As Object
Dim Units As Object
' Normalize input
Words = LCase(Trim(Words))
Words = Replace(Words, " and ", " ")
WordList = Split(Words, " ")
' Create word-to-number mappings
Set Multipliers = CreateObject("Scripting.Dictionary")
Multipliers.Add "crore", 10000000#
Multipliers.Add "lakh", 100000#
Multipliers.Add "thousand", 1000#
Multipliers.Add "hundred", 100#
Set Units = CreateObject("Scripting.Dictionary")
Units.Add "zero", 0
Units.Add "one", 1
Units.Add "two", 2
Units.Add "three", 3
Units.Add "four", 4
Units.Add "five", 5
Units.Add "six", 6
Units.Add "seven", 7
Units.Add "eight", 8
Units.Add "nine", 9
Units.Add "ten", 10
Units.Add "eleven", 11
Units.Add "twelve", 12
Units.Add "thirteen", 13
Units.Add "fourteen", 14
Units.Add "fifteen", 15
Units.Add "sixteen", 16
Units.Add "seventeen", 17
Units.Add "eighteen", 18
Units.Add "nineteen", 19
Units.Add "twenty", 20
Units.Add "thirty", 30
Units.Add "forty", 40
Units.Add "fifty", 50
Units.Add "sixty", 60
Units.Add "seventy", 70
Units.Add "eighty", 80
Units.Add "ninety", 90
Temp = 0
Num = 0
For i = 0 To UBound(WordList)
CurrentWord = WordList(i)
If Units.exists(CurrentWord) Then
Temp = Temp + Units(CurrentWord)
ElseIf Multipliers.exists(CurrentWord) Then
If CurrentWord = "hundred" Then
Temp = Temp * Multipliers(CurrentWord)
Else
Num = Num + Temp * Multipliers(CurrentWord)
Temp = 0
End If
End If
Next i
ConvertIndianWordsToNumber = Num + Temp
End Function
Steps
1. Click on Copy the VB Code.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt + F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code.
7. After the Number column use ConverttoIndianwordstoNumber formula.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt + F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code.
7. After the Number column use ConverttoIndianwordstoNumber formula.
Calculate Age in Years, Months, Days
Function ExactAge(ByVal DOB As Date) As String
Dim y As Integer, m As Integer, d As Integer
Dim today As Date: today = Date
y = Year(today) - Year(DOB)
m = Month(today) - Month(DOB)
d = Day(today) - Day(DOB)
If d < 0 Then
m = m - 1
d = d + Day(DateSerial(Year(today), Month(today), 0))
End If
If m < 0 Then
y = y - 1
m = m + 12
End If
ExactAge = y & " years, " & m & " months, " & d & " days"
End Function
Steps
1. Click on Copy the VB Code.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt + F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code.
7. After the date column use =ExtractAge formula.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt + F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code.
7. After the date column use =ExtractAge formula.
Extract Only Numbers from Text
Function ExtractNumbers(cell As String) As String
Dim i As Integer, output As String
For i = 1 To Len(cell)
If Mid(cell, i, 1) Like "#" Then output = output & Mid(cell, i, 1)
Next i
ExtractNumbers = output
End Function
Steps
1. Click on Copy the VB Code.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the Number column use =ExtractNumbers.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the Number column use =ExtractNumbers.
Convert to Proper Case (Better than Excel’s PROPER)
Function SmartProper(ByVal txt As String) As String
Dim arr, i As Integer
Dim smallWords As Variant
smallWords = Array("of", "the", "in", "and", "on", "for")
arr = Split(LCase(txt), " ")
For i = 0 To UBound(arr)
If i = 0 Or IsError(Application.Match(arr(i), smallWords, 0)) Then
arr(i) = UCase(Left(arr(i), 1)) & Mid(arr(i), 2)
End If
Next
SmartProper = Join(arr, " ")
End Function
Steps
1. Click on Copy the VB Code.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the Number column use =smartproper.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the Number column use =smartproper.
Convert Date to Words
Function DateToWords(d As Date) As String
Dim dayWords As Variant
dayWords = Array("Zero", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", _
"Tenth", "Eleventh", "Twelfth", "Thirteenth", "Fourteenth", "Fifteenth", "Sixteenth", _
"Seventeenth", "Eighteenth", "Nineteenth", "Twentieth", "Twenty First", "Twenty Second", _
"Twenty Third", "Twenty Fourth", "Twenty Fifth", "Twenty Sixth", "Twenty Seventh", _
"Twenty Eighth", "Twenty Ninth", "Thirtieth", "Thirty First")
DateToWords = dayWords(Day(d)) & " " & Format(d, "mmmm") & " " & ConvertYearToWords(Year(d))
End Function
Function ConvertYearToWords(ByVal yearVal As Integer) As String
Dim firstPart As Integer, secondPart As Integer
Dim result As String
firstPart = Int(yearVal / 100)
secondPart = yearVal Mod 100
result = ConvertTensToWords(firstPart)
If secondPart <> 0 Then
result = result & " " & ConvertTensToWords(secondPart)
End If
ConvertYearToWords = result
End Function
Function ConvertTensToWords(ByVal number As Integer) As String
Dim ones As Variant
Dim tens As Variant
Dim result As String
ones = Array("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", _
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
If number < 20 Then
result = ones(number)
Else
result = tens(Int(number / 10))
If number Mod 10 > 0 Then
result = result & " " & ones(number Mod 10)
End If
End If
ConvertTensToWords = result
End Function
Steps
1. Click on Copy the VB Code.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the date column use =Datetowords.
2. Click Ok on the alert message.
3. Open the excel file where number needs to be converted.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. After the date column use =Datetowords.
Ledger OB Balance template creation for SAP B1
Sub GenerateSAPTemplate()
Dim wsInput As Worksheet, wsOutput As Worksheet
Dim lastRow As Long, i As Long, outputRow As Long
Dim cutoffDate As String, sapCode As String, drcr As String
Dim amount As Double, formattedDate As String
' Set worksheets
Set wsInput = ThisWorkbook.Sheets("Sheet1")
' Create or clear Sheet2
On Error Resume Next
Set wsOutput = ThisWorkbook.Sheets("Sheet2")
If wsOutput Is Nothing Then
Set wsOutput = ThisWorkbook.Sheets.Add(After:=wsInput)
wsOutput.Name = "Sheet2"
Else
wsOutput.Cells.Clear
End If
On Error GoTo 0
' Set headers
wsOutput.Range("A1:E1").Value = Array("Duedate", "Code", "Name", "Balance(LC)", "OB (LC)")
lastRow = wsInput.Cells(wsInput.Rows.Count, "A").End(xlUp).Row
outputRow = 2
' Loop through data rows
For i = 2 To lastRow
If wsInput.Cells(i, "A").Value <> "" Then
' Get values
cutoffDate = wsInput.Cells(i, "A").Value
sapCode = wsInput.Cells(i, "C").Value
drcr = Trim(LCase(wsInput.Cells(i, "D").Value))
amount = wsInput.Cells(i, "E").Value
' Format date to YYYYMMDD
On Error Resume Next
formattedDate = Format(DateValue(cutoffDate), "yyyymmdd")
On Error GoTo 0
' Make amount negative if Cr
If drcr = "cr" Then
amount = -Abs(amount)
ElseIf drcr = "dr" Then
amount = Abs(amount)
End If
' Fill output sheet
With wsOutput
.Cells(outputRow, 1).Value = formattedDate
.Cells(outputRow, 2).Value = sapCode
.Cells(outputRow, 3).Value = "" ' Name blank
.Cells(outputRow, 4).Value = "" ' Balance(LC) blank
.Cells(outputRow, 5).Value = amount
End With
outputRow = outputRow + 1
End If
Next i
MsgBox "SAP B1 Template Generated in Sheet2", vbInformation
End Sub
Steps
Note: User Inputs should as Cut off date, Opening balance ledger code, SAP G/L Code,DR/CR, Amount in excel rows.
1. Click on Copy the VB Code here.
2. Click Ok on the alert message.
3. Open the excel file where extraction need to be done.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. Type Alt+F8 for macors and click on run.
2. Click Ok on the alert message.
3. Open the excel file where extraction need to be done.
4. Type Alt+F11.
5. Click on Insert and Select module from menu bar.
6. Paste the code & close the window.
7. Type Alt+F8 for macors and click on run.
