You are on page 1of 13

This file contains some VBA Functions that can be used with Excel.

Save the file with the .bas extension. For example, MyFuntions.bas Then, open a new Excel workbook. Press Alt + F11 to open the Macro Editor. From the File menu, select Import file and then choose MyFunctions.bas Now, the functions will be available in the workbook. ================================================================================ ========

Attribute VB_Name = "MyFunctions" Option Explicit Option Base 1 'This function calculates the LTD premium (including the 'provincial tax Function LTD_DED(Period$, Optional AvgComm As Single, Optional PayRate As Varian t, Optional STDHRS, Optional PaysPerYear As Variant, _ Optional Prov As Variant, Optional AnnSal As Variant) As Currency Attribute LTD_DED.VB_Description = "Calculates the LTD premium with the PST incl uded." Dim Prem As Double, Cov As Double, ProvTax As Single, PaysPerMonth% Dim Hours! Dim Commission Select Case Period Case "M" PaysPerMonth = 1 Hours = 1 Case "NHF" PaysPerMonth = 4 PaysPerYear = 52 If IsMissing(STDHRS) Then Hours = 40 Else: Hours = STDHRS End If Case "NHE" PaysPerMonth = 2 PaysPerYear = 26 Hours = 1 End Select ' Evaluate Prov. If IsMissing(Prov) Then ProvTax = 0# Else Select Case Prov Case "ON", "ONT", 76, "76" ProvTax = 0.08 Case "PQ", "QUE", 78, "78" ProvTax = 0.09 Case Else ' Other values. ProvTax = 0# End Select End If 'Evaluate AvgComm and AnnSal If IsMissing(AvgComm) Then Commission = 0#

Else Commission = AvgComm End If If IsMissing(AnnSal) Then AnnSal = (PayRate * Hours * PaysPerYear) End If Prem = 1.14 'This is the LTD premium per hundred of coverage Cov = Application.Min((AnnSal + Commission) / 12 * 0.6, 7000) 'The monthly c overage 'Following is the LTD formula LTD_DED = Application.Round((Cov / 100 * Prem * (1# + ProvTax)) / PaysPerMon th, 2) End Function 'This macro combines the Index function and the Match function. 'Use it in place of Vlookup Function LookItUp(lookuparea As Object, LookupItem As Object, _ ItemCol As Object, ColNum As Integer) As Variant Dim Ritem As Integer, Answer As Integer Ritem = Application.Match(LookupItem.Value, ItemCol, 0) Answer = Application.Index(lookuparea, Ritem, ColNum) If Application.IsError(Answer) Then LookItUp = 0 Else LookItUp = Answer End If End Function Function ReturnCellColur(aCell As Range) ReturnCellColur = aCell.Interior.Color End Function Function VacPercent(HireDate As Date, EndDate As Date) As Single Dim Vper As Double, Seniority As Single Seniority = (EndDate - HireDate) / 365 If Seniority < 5 Then Vper = 0.06 ElseIf Seniority < 20 Then Vper = 0.08 Else Vper = 0.1 End If VacPercent = Vper End Function Function DataList() As MailingList Dim iList As MailingList Dim Tmp As Variant With iList 'get the first name Tmp = InputBox(PROMPT:="Enter the First name.", Title:=iTitle) If Tmp = "" Then 'did the user cancel? Tmp = MsgBox(PROMPT:="End data Entry?", Title:=iTitle, _ Buttons:=vbQuestion + vbYesNo) If Tmp = vbYes Then 'return null first name .fName = ""

DataList = iList Exit Function End If End If .fName = Tmp 'fill First Name field 'get the last name Tmp = InputBox(PROMPT:="Enter the Last name.", Title:=iTitle) If Tmp = "" Then 'did the user cancel? Tmp = MsgBox(PROMPT:="End data Entry?", Title:=iTitle, _ Buttons:=vbQuestion + vbYesNo) If Tmp = vbYes Then 'return null Last name .lName = "" DataList = iList Exit Function End If End If .lName = Tmp 'fill Last Name field 'get the company name Tmp = InputBox(PROMPT:="Enter the company name.", Title:=iTitle) If Tmp = "" Then 'did the user cancel? Tmp = MsgBox(PROMPT:="End data Entry?", Title:=iTitle, _ Buttons:=vbQuestion + vbYesNo) If Tmp = vbYes Then 'return null company name .CoName = "" DataList = iList Exit Function End If End If .CoName = Tmp 'fill company Name field 'get the street address Tmp = InputBox(PROMPT:="Enter the street address.", Title:=iTitle) If Tmp = "" Then 'did the user cancel? Tmp = MsgBox(PROMPT:="End data Entry?", Title:=iTitle, _ Buttons:=vbQuestion + vbYesNo) If Tmp = vbYes Then 'return null street address .Street = "" DataList = iList Exit Function End If End If .Street = Tmp 'fill Street Name field 'get the city Tmp = InputBox(PROMPT:="Enter the city name.", Title:=iTitle) If Tmp = "" Then 'did the user cancel? Tmp = MsgBox(PROMPT:="End data Entry?", Title:=iTitle, _ Buttons:=vbQuestion + vbYesNo) If Tmp = vbYes Then 'return null city name .lName = "" DataList = iList Exit Function End If End If .City = Tmp 'fill City Name field 'get the state Tmp = InputBox(PROMPT:="Enter the state.", Title:=iTitle)

If Tmp = "" Then 'did the user cancel? Tmp = MsgBox(PROMPT:="End data Entry?", Title:=iTitle, _ Buttons:=vbQuestion + vbYesNo) If Tmp = vbYes Then 'return null state name .State = "" DataList = iList Exit Function End If End If .State = Tmp 'fill State Name field 'get the zip code Tmp = InputBox(PROMPT:="Enter the postal code.", Title:=iTitle) If Tmp = "" Then 'did the user cancel? Tmp = MsgBox(PROMPT:="End data Entry?", Title:=iTitle, _ Buttons:=vbQuestion + vbYesNo) If Tmp = vbYes Then 'return null zip code .ZIP = "" DataList = iList Exit Function End If End If .ZIP = Tmp 'fill ZIP field End With DataList = iList End Function '---------------------------------------------------------------------Function ReverseStr(rStr As String) As String 'reverses the order of characters in the Str argument Dim k&, tStr$ tStr = "" For k = 1 To Len(Trim(rStr)) tStr = Mid(rStr, k, 1) & tStr Next k ReverseStr = tStr End Function Function RevNameLast(Str As String) As String 'Puts last name before first name Dim N As String Dim L As Integer, F As Integer, lStr As String Dim fStr As String, S As Integer N = " " L = Len(Trim(Str)) S = Application.Find(N, Str) 'Position of space in name. F = L - S 'Number of characters in last name. lStr = Mid(Str, S + 1, F) 'Last name fStr = Mid(Str, 1, S - 1) 'First name RevNameLast = lStr & "," & fStr 'last name followed by first name. End Function Function RevNameFirst(eName As String) As String 'Puts first name before last name Dim N As String Dim L As Integer, F As Integer, lStr As String Dim fStr As String, S As Integer

N = "," L = Len(Trim(eName)) S = Application.Find(N, eName) 'Position of space in name. F = L - S 'Number of characters in first name. fStr = Mid(eName, S + 1, F) 'First name lStr = Mid(eName, 1, S - 1) 'Last name RevNameFirst = fStr & " " & lStr 'First name followed by last name. End Function Function QueTaxBen(CoCode$, BenCode$, ProvCode$) As Currency 'Determines the YTD benefit deduction at week 3 Dim Ded@ If ProvCode = "78" Then Select Case CoCode Case "NHE" Select Case BenCode Case "A" Ded = 10.44 Case "B" Ded = 39.82 Case "C" Ded = 38.41 Case "D" Ded = 35.19 Case "E" Ded = 20.87 Case "F" Ded = 70.5 Case "G" Ded = 67.68 Case "H" Ded = 61.23 Case "I" Ded = 25.59 Case "J" Ded = 92.33 Case "K" Ded = 87.7 Case "L" Ded = 75.42 Case Else Ded = 0 End Select Case "NHF" Ded = 0 End Select End If QueTaxBen = Ded End Function

Function BenDed(CoCode$, BenCode$, PayPeriods%) As Currency Attribute BenDed.VB_Description = "Calculates the Mod Ben deduction for a specif ied number of pay periods." 'Determines the YTD benefit deduction at week 3 Dim Ded@ Select Case CoCode

Case "NHE" Select Case BenCode Case "F", "G", "H" Ded = 9.12 Case "J", "K", "L" Ded = 15.62 Case Else Ded = 0 End Select Case "NHF" Select Case BenCode Case "F", "G", "H" Ded = 4.56 Case "J", "K", "L" Ded = 7.81 Case Else Ded = 0 End Select End Select BenDed = Ded * PayPeriods End Function Function TaxBenLife(CoCode$, BenCode$, ProvCode$, Optional PayRate, Optional STD HRS, Optional AvgComm, Optional AnnSal) As Currency Dim LifeRate!, Coverage%, PTax! LifeRate = 0.14 If IsMissing(AvgComm) Then AvgComm = 0 End If '=========================================================================== ============ If ProvCode = "76" Then PTax = 1.08 ElseIf ProvCode = "78" Then PTax = 1.09 Else PTax = 1 End If '=========================================================================== ============= 'Life insurance coverage is 2 times annual salary. Coverage = 2 '=========================================================================== ============= If IsMissing(AnnSal) Then If CoCode = "NHE" Then TaxBenLife = Application.Round(((PayRate * 26) + AvgComm) * Coverage / 1000 * LifeRate / 2 * PTax, 2) ElseIf CoCode = "NHF" Then TaxBenLife = Application.Round(PayRate * STDHRS * 52 * Coverage / 10 00 * LifeRate / 4 * PTax, 2) End If Else If CoCode = "NHE" Then TaxBenLife = Application.Round((AnnSal + AvgComm) * Coverage / 1000 * LifeRate / 2 * PTax, 2) ElseIf CoCode = "NHF" Then

TaxBenLife = Application.Round(AnnSal * Coverage / 1000 * LifeRate / 4 * PTax, 2) End If End If End Function Function LifeVolume(DataControl, Salary, Commission) As Long 'Calculates the life volume based on the Data Control Code Dim TotSal@ TotSal = Salary + Commission Select Case Right(DataControl, 1) Case "A" To "C" LifeVolume = TotSal Case "D" To "I" LifeVolume = TotSal * 2 Case Else LifeVolume = 0 End Select End Function Function VacationEntitlement(Date5 As Date, CurrentDate As Date) As Currency 'Calculates the monthly vacation entitlement Dim LOS As Integer LOS = (CurrentDate - Date5) \ 365 Select Case LOS Case 0 To 5 VacationEntitlement = 1.25 Case 5 To 20 VacationEntitlement = 1.67 Case Else VacationEntitlement = 2.08 End Select End Function Function MaximumVacAccr(MonthlyEntitlement) 'Calculates the maximum allowable accrual Select Case MonthlyEntitlement Case 1.25 MaximumVacAccr = 18.75 Case 1.67 MaximumVacAccr = 25 Case 2.08 MaximumVacAccr = 31.25 End Select End Function Function MonthName() Dim Result As String Dim RepMonth As Variant RepMonth = Array("January", "February", "March", "April", "May", "June", "Ju ly", "August", _ "September", "October", "November", "December") Result = InputBox(PROMPT:="Enter the month for this report.", _ Default:=RepMonth(Month(Now)), Title:="REPORT MONTH") If Result = "" Then End End If

MonthName = Result End Function Function ConvertToNumber(aNumber As String) As Currency Attribute ConvertToNumber.VB_Description = "Converts a negative number that is f ormatted as text with the minus sign on the right to a value." ConvertToNumber = CCur(aNumber) End Function Function WeightIndex(WeightInPounds As Single, Optional HeightInInches As Single = 70) As Single Dim MetricWeight As Single Dim MetricHeight As Single MetricWeight = Application.Convert(WeightInPounds, "lbm", "kg") MetricHeight = Application.Convert(HeightInInches, "in", "m") 'WeightIndex = MetricWeight / (MetricHeight * MetricHeight) WeightIndex = MetricWeight

End Function Function SickReportDept(Clocknum As String) As String Select Case CInt(Left(Clocknum, 4)) Case 219, 221, 300, 1800 To 1899 SickReportDept = "CD Mfg" Case 213, 326, 1300 To 1399 SickReportDept = "Printing" Case 222, 1500 To 1799 SickReportDept = "Maintenance" Case 712, 1600 To 1699 SickReportDept = "Warehouse" Case 411 SickReportDept = "Facilities" Case 412 SickReportDept = "Security" Case Else SickReportDept = "Xclude" End Select End Function Function DataRange(Optional ByVal aSheet As Variant, Optional ByVal rStartRange As Variant) As Range Attribute DataRange.VB_Description = "Returns the range for data in a column of aSheet, using rStartRange as the top of the range. The bottom of the range is f ound by starting at row 16384 and moving up to the first cell containing data. For this function\r\nto return the correct range, there must not be any data in any cells below the range of data that will be defined." 'returns the range for data in a column of aSheet, using rStartRange as the top of the 'range. The bottom of the range is found by starting at row 16384 'and moving up to the first cell containing data. For this function 'to return the correct range, there must not be data in any cells 'below the range of data that will be defined. Dim sBookName As String, sSheetName As String Dim sTopCell As String, sBottomCell As String Dim iColumn As Integer Const stitle = "Source File Information"

Const sBookPrompt = "Enter the name of the source workbook." Const sSheetPrompt = "Enter the name of the data sheet in the source workboo k." Const sTopCellPrompt = "Enter the address of the top cell " & _ "in the data range." On Error GoTo INCORRECTARGUMENTS rksheet name 'error trap for incorrect workbook or wo

'If aSheet and rStartRange are not provided, the user is prompted for 'the name of the workbook, the name of the sheet, and the address of the cel l at 'the top of the coloumn of data to be defined. If IsMissing(aSheet) Then 'Get the name of the source workbook: sBookName = InputBox(PROMPT:=sBookPrompt, Title:=stitle, Default:=sBookN ame) 'End the procedure if the user cancels: If sBookName = "" Then GoTo USERCANCELLED 'Get the name of sheet containing the data in the source workbook: sSheetName = InputBox(PROMPT:=sSheetPrompt, Title:=stitle, Default:=sShe etName) 'End the procedure if the user cancels: If sSheetName = "" Then GoTo USERCANCELLED Set aSheet = Workbooks(sBookName).Sheets(sSheetName) End If If IsMissing(rStartRange) Then 'Get the address of the cell at the top of the data range sTopCell = InputBox(PROMPT:=sTopCellPrompt, Title:=stitle, Default:=sTop Cell) 'End the procedure if the user cancels: If sTopCell = "" Then GoTo USERCANCELLED Set rStartRange = aSheet.Range(sTopCell) Else sTopCell = rStartRange.Address 'the top of the data range column End If iColumn = rStartRange.Column 'the column of the data range

sBottomCell = aSheet.Cells(16384, iColumn).End(xlUp).Address Set DataRange = aSheet.Range(sTopCell & ":" & sBottomCell) On Error GoTo 0 Exit Function INCORRECTARGUMENTS: 'The worksheet received in the aSheet argument does not exist or is not open MsgBox "The name for the workbook or worksheet is incorrect " & _ "or the the workbook is not open. Procedure ended." End USERCANCELLED: 'If the user cancels a prompt, end the procedure. MsgBox "Procedure cancelled." End End Function Function IsDiskFile(fName As String) As Boolean

'return True if fName is found on disk, False otherwise If (Dir(fName) <> "") Then IsDiskFile = True Else IsDiskFile = False End If End Function Function IsFileOpen(fName As String) As Boolean 'return True if fName is found on disk, False otherwise Dim aBook As Workbook For Each aBook In Workbooks If UCase(aBook.Name) = UCase(fName) Then IsFileOpen = True Exit For Else IsFileOpen = False End If Next aBook End Function Function DaysToHoursAndMinutes(STDHRS As Integer, Days As Double) As String 'Converts the Days to hours and minutes: Dim iHours As Integer Dim iMinutes As Single Dim UnknownHours As Boolean Dim DecPt As String Dim SpecNum As Single 'variable to hold either .001 or -0.001 If Days < 0 Then SpecNum = -0.001 Else SpecNum = 0.001 End If UnknownHours = False Select Case STDHRS Case 37.5, 75 '7.5 hours per day iHours = Fix(Days * 7.5) iMinutes = Application.Round(((Days * 7.5) - iHours) * 0.6, 2) + Spe cNum Case 36 '7.2 hours per day (4 shifts of 12 hours each) iHours = Fix(Days * 7.2) iMinutes = Application.Round(((Days * 7.2) - iHours) * 0.6, 2) + Spe cNum Case 40, 80 '8 hours per day iHours = Fix(Days * 8) iMinutes = Application.Round(((Days * 8) - iHours) * 0.6, 2) + SpecN um Case Else 'unknown standard hours UnknownHours = True End Select 'Find the position of the decimal poFix in the minutes: DecPt = InStr(1, CStr(iMinutes), ".") If UnknownHours = False Then

DaysToHoursAndMinutes = CStr(iHours) & ":" & Mid(CStr(iMinutes), DecPt + 1, 2) Else DaysToHoursAndMinutes = "Unknown" End If End Function Function EmpID(CoCode$, FileNum As Long) As String Dim fLen As Integer, nZeroes As Integer 'Get the length of the file number: fLen = Len(Trim(FileNum)) 'Determine how many zeroes should precede the file number: nZeroes = 6 - fLen 'Create the employee ID: EmpID = CoCode & "-" & String(nZeroes, "0") & FileNum End Function Function DefaultPeriod() As String Dim DefMth$, DefYr$ If Month(Now) < 4 Then DefMth$ = Format(Month(Now) + 9, "00") DefYr$ = Format(Year(Now), "00") Else DefMth$ = Format(Month(Now) - 3, "00") DefYr$ = Format(Right(Year(Now) + 1, 2), "00") End If DefaultPeriod = DefYr$ & DefMth$ End Function Function VacationHours(STDHRS As Integer, VacationDays As Double) As String 'Converts the VacationDays to hours and minutes: Dim iHours As Integer Dim iMinutes As Single Dim UnknownHours As Boolean Dim DecPt As String Dim SpecNum As Single 'variable to hold either .001 or -0.001 If VacationDays < 0 Then SpecNum = -0.001 Else SpecNum = 0.001 End If UnknownHours = False Select Case STDHRS Case 75 '7.5 hours per day iHours = Fix(VacationDays * 7.5) iMinutes = Application.Round(((VacationDays * 7.5) - iHours) * 0.6, 2) + SpecNum Case 36 '7.2 hours per day (4 shifts of 12 hours each) iHours = Fix(VacationDays * 7.2) iMinutes = Application.Round(((VacationDays * 7.2) - iHours) * 0.6, 2) + SpecNum Case 40, 80 '8 hours per day iHours = Fix(VacationDays * 8) iMinutes = Application.Round(((VacationDays * 8) - iHours) * 0.6, 2)

+ SpecNum Case Else 'unknown standard hours UnknownHours = True End Select 'Find the position of the decimal poFix in the minutes: DecPt = InStr(1, CStr(iMinutes), ".") If UnknownHours = False Then VacationHours = CStr(iHours) & ":" & Mid(CStr(iMinutes), DecPt + 1, 2) Else VacationHours = "Unknown" End If End Function Function ReturnPercentage(FirstValue As Currency, LastValue As Currency, NoOfYea rs As Integer) Dim aRate As Currency Dim TempValue As Currency aRate = 0.0001 Do aRate = aRate + 0.0001 TempValue = Application.Power(FirstValue + aRate, NoOfYears) Loop While Application.Round(TempValue, 2) < LastValue ReturnPercentage = Application.Round(aRate, 2) End Function Public Function smatch(svalue As Variant, stitle As Variant, Optional ValCol As Range, Optional TitleRow As Range, Optional aRange) As Variant Dim r As Long Dim c As Integer Dim aCol As Integer Dim arow As Long aCol = ValCol.Column arow = TitleRow.Row 'Set arange = Range("a:z") For r = 1 To aRange.Rows.Count If UCase$(aRange.Cells(r, aCol).Value) = UCase$(svalue) Then Exit For Next r For c = 1 To 26 'arange.Columns.Count If UCase$(aRange.Cells(arow, c).Value) = UCase$(stitle) Then Exit For Next c smatch = aRange.Cells(r, c) End Function Public Function smatchV2(svalue As Variant, stitle As Variant, Optional ValCol A s Range, Optional TitleRow As Range, Optional aRange) As Variant Dim r As Long Dim c As Integer

Dim aCol As Integer Dim arow As Long aCol = ValCol.Column arow = TitleRow.Row 'Set arange = Range("a:z") For r = 1 To aRange.Rows.Count If UCase$(aRange.Cells(r, aCol).Value) = UCase$(svalue) Then Exit For Next r For c = 1 To 26 'arange.Columns.Count If UCase$(aRange.Cells(arow, c).Value) = UCase$(stitle) Then Exit For Next c smatchV2 = aRange.Cells(r, c) End Function

You might also like