Access Excel VBA Check Prime Number using custom Function

This tutorial shows a custom Access Excel VBA Function that can check prime number, the Function returns TRUE or FALSE.

Access Excel VBA Check Prime Number using custom Function

In this tutorial, I will show a custom Access Excel Function that can check prime number, returning TRUE or FALSE. Prime number is an integer that can only be divided by 1 or itself (without remainder). Below are some examples of prime number.

1–20235711131719232931374143475359616771
21–407379838997101103107109113127131137139149151157163167173
41–60179181191193197199211223227229233239241251257263269271277281
61–80283293307311313317331337347349353359367373379383389397401409

http://en.wikipedia.org/wiki/List_of_prime_numbers

Access Excel VBA Function Code – Check Prime Number

Public Function wIsPrimeNumber(sinput) As Boolean
    wIsPrimeNumber = True
    If sinput = 1 Then
        wIsPrimeNumber = False
    ElseIf sinput > 2 Then
        For i = 2 To sinput - 1
            If sinput Mod i = 0 Then
                wIsPrimeNumber = False
                Exit Function
            End If
        Next i
    End If
End Function

VBA Function Code Algorithm – Check Prime Number

Below is what I have done in the Function. This code is 100% original and I originally created it for a question posted in Microsoft Community. I did not even google for similar Function, let me know if you see any holes I am not aware of.

– Function wIsPrimeNumber returns TRUE or FALSE

– Function returns TRUE by default, unless it falls into IF criteria

– Divide the user input number by 1,2,3,…until number itself-1 , if no reminder for all the calculations, then it should be a prime number,  no action is needed because default is already TRUE (is prime number)

– Otherwise if any one of those calculations have no remainder, then it is not a prime number, and the Function returns FALSE

VBA Function Syntax – Check Prime Number

wIsPrimeNumber (sInput)

sInput is the number you want to check whether it is a Prime Number

Example – Check Prime Number

FormulaResult
=wisprimenumber(5)TRUE
=wisprimenumber(6)FALSE
=IF(wisprimenumber(5),”Prime Number”,”Not Prime Number”)Prime Number
=IF(not(wisprimenumber(5)),”Not Prime Number”,”Prime Number”)Prime Number

 

VBA Access Excel Remove duplicates in text

This tutorial provides a custom Access Excel VBA Function to remove duplicates in text, parameters provide flexibility of case sensitivity and delimiter

You may also want to read:

Access Excel Scripting Dictionary store unique array item

VBA Access Excel remove duplicates in text

This tutorial is to help you to remove duplicates in text (in a Cell), but it is not about removing duplicated Cell value in a column. To remove duplicated Cell value in a column, highlight the column, navigate to menu Data > Remove Duplicates.

Below is an example of duplicate in text, lets say Cell A1 contains the followings

Mary, Ann, MAry, Peter, Mary,PETER,   Mary

You can see that Mary has been duplicated for 3 times differently, so is Peter. Our goal is to return only one Mary and Peter, as well as other non duplicated value.

VBA Function Code – remove duplicates in text

The below code makes use of the unique properties of associative array Dictionary that Key cannot be duplicate.

The purpose is to create an associate array called objDict to add delimited items as Key. If Item already exists, do not return the item in Function.

Public Function wUniqueStr(sinput As String, delimiter As String, Optional Compare As Integer = 0) As String
    Dim objDict As Object
    Dim arrInput As Variant
    Dim uniqStr As String
    arrInput = Split(sinput, delimiter)
    Set objDict = CreateObject("Scripting.Dictionary")
    If Compare = 0 Then 'case insensitive
        For i = 0 To UBound(arrInput) 
                If objDict.exists(UCase(Trim(arrInput(i)))) Then
            Else
                objDict.Add UCase(Trim(arrInput(i))), i
                uniqStr = uniqStr & arrInput(i) & delimiter
            End If
        Next i
        wUniqueStr = Left(uniqStr, Len(uniqStr) - Len(delimiter))
    Else  'case sensitive
        For i = 0 To UBound(arrInput)
                If objDict.exists(Trim(arrInput(i))) Then
            Else
                objDict.Add Trim(arrInput(i)), i
                uniqStr = uniqStr & arrInput(i) & delimiter
            End If
        Next i
        wUniqueStr = Left(uniqStr, Len(uniqStr) - Len(delimiter))
    End If
End Function

Syntax of Access Excel VBA Function – remove duplicates in text

wUniqueStr(sinput, delimiter, [Compare])

sinputThe text you want to remove duplicate
delimiterThe seperator (delimiter) that separates each value
CompareOptional. Default is 0, case insensitive. Type 1 for case sensitive

Example of Access Excel VBA Function – remove duplicates in text

Assume you have the followings in Cell A1

Mary , Ann, MAry, Peter,  Mary,PETER,   Mary

 

FormulaReturn Value
=wUniqueStr(A1,”,”,1)Mary , Ann, MAry, Peter,PETER
=wUniqueStr(A1,”,”)Mary , Ann, Peter

Note the followings

– Any “Mary ” and “Mary ” (with space in front or behind) is regarded as the same text, only the left most version (first occurrence) of “Mary” is returned

– “Peter” and “PETER” are regarded as same value if the third parameter is “1” (case sensitive)

Outbound References

http://answers.microsoft.com/en-us/office/forum/office_2010-excel/delete-duplicate-value-in-a-row/a79acf8e-8dfd-4c4b-b8c0-e250dabe98dc

 

Access Excel VBA extract number from text or extract alphabet

This tutorial shows several Access Excel VBA custom functions to extract number from text, extract alphabet from text, extract symbols from text

Excel Access VBA extract percentage from text

Excel Extract Time from Date Time or Extract Date

Access Excel extract file name from file path

Access Excel VBA extract number from text or extract alphabet from text

In this article, I will show a list of custom Functions to perform the following tasks.

– Check if a text contains any alphabet, if a text contains only alphabets, extract alphabet from text

– Check if a text contains any symbols, extract symbols from text

– Check if a text contains any number, if a text contains only number, extract number from text, extract number from text and then sum only the number part in a Range (sum text).

These functions are useful in data verification. For example, you may want to check if an employee ID contains only number. You may also want to check if employee name does not contain symbols. Some function are based on ASC Function for checking of alphabets and symbols.

1.1 Check if a text contains any alphabet

The below function checks if a text contains alphabet, regardless of capital letter or small letter. This function returns TRUE if an alphabet is found, otherwise returns FALSE.

Public Function wCheckAlphabet(var)
    For i = 1 To Len(var)
        If Asc(Mid(UCase(var), i, 1)) >= 65 And Asc(Mid(UCase(var), i, 1)) <= 90 Then
            wCheckAlphabet = True
            Exit Function
        Else
            wCheckAlphabet = False
        End If
    Next i
End Function

1.2 Check if a text contains ONLY alphabets

The below function checks if a text contains only alphabets, regardless of capital letter or small letter. This function returns TRUE if only alphabets are found in the text, otherwise returns FALSE.

Public Function wCheckOnlyAlphabet(var)
    For i = 1 To Len(var)
        If Asc(Mid(UCase(var), i, 1)) >= 65 And Asc(Mid(UCase(var), i, 1)) <= 90 Then
            wCheckOnlyAlphabet = True
        Else
            wCheckOnlyAlphabet = False
            Exit Function
        End If
    Next i
End Function

1.3 Extract alphabet from Text

Public Function wExtractAlphabet(var)
    For i = 1 To Len(var)
        If Asc(Mid(UCase(var), i, 1)) >= 65 And Asc(Mid(UCase(var), i, 1)) <= 90 Then
            result = result & Mid(var, i, 1)
        End If
    Next i
    wExtractAlphabet = result
End Function

2.1 Check if a text contains any symbols

The below function checks if a text contains the below symbols, return TRUE if any one of the below is found.

!+?}
,@~
#[
$.\
%/]
&:^
;_
(<`
)={
*>|

 

Public Function wCheckSymbol(var)
    For i = 1 To Len(var)
        If (Asc(Mid(var, i, 1)) >= 33 And Asc(Mid(var, i, 1)) <= 47) Or _
        (Asc(Mid(var, i, 1)) >= 58 And Asc(Mid(var, i, 1)) <= 64) Or _
        (Asc(Mid(var, i, 1)) >= 91 And Asc(Mid(var, i, 1)) <= 96) Or _
        (Asc(Mid(var, i, 1)) >= 123 And Asc(Mid(var, i, 1)) <= 126) Then
            wCheckSymbol = True
            Exit Function
        Else
            wCheckSymbol = False
        End If
    Next i
End Function

2.2 Extract symbols from text

Public Function wExtractSymbol(var)
    For i = 1 To Len(var)
        If (Asc(Mid(var, i, 1)) >= 33 And Asc(Mid(var, i, 1)) <= 47) Or _
        (Asc(Mid(var, i, 1)) >= 58 And Asc(Mid(var, i, 1)) <= 64) Or _
        (Asc(Mid(var, i, 1)) >= 91 And Asc(Mid(var, i, 1)) <= 96) Or _
        (Asc(Mid(var, i, 1)) >= 123 And Asc(Mid(var, i, 1)) <= 126) Then
            result = result & Mid(var, i, 1)
        End If
    Next i
    wExtractSymbol = result
End Function

3.1 Check if a text contains any number

The below function checks if a text contains number. This function returns TRUE if a number is found, otherwise returns FALSE.

Public Function wCheckNumber(var)
    For i = 1 To Len(var)
        If Asc(Mid(var, i, 1)) >= 0 And Asc(Mid(var, i, 1)) <= 9 Then
            wCheckNumber = True
            Exit Function
        Else
            wCheckNumber = False
        End If
    Next i
 End Function

3.2 Check if a text contains ONLY number

The below function checks if a text contains only number. This function returns TRUE if only number is found, otherwise returns FALSE.

Public Function wCheckOnlyNumber(var)
    For i = 1 To Len(var)
        If Asc(Mid(var, i, 1)) >= 0 And Asc(Mid(var, i, 1)) <= 9 Then
            wCheckOnlyNumber = True
        Else
            wCheckOnlyNumber = False
            Exit Function
        End If
    Next i
End Function

3.3 Extract number from text

The below Function extracts number from a text. For example, =wExtractNumber(“#123”) would return 123

Public Function wExtractNumber(sinput) As Double
For i = 1 To Len(sinput)
If IsNumeric(Mid(sinput, i, 1)) Then
result = result & Mid(sinput, i, 1)
End If
Next i
wExtractNumber = result
End Function

3.4 Sum number from text in a Range (sum text) – For Excel only

The below Function is used like the regular SUM Function, except that it sums only the number part of the text. You have to also copy the above Function ExtractNumber in order for the below Function to work.

Public Function wSumExtractNumber(sinput As Range) As Double
    For Each Rng In sinput
        If IsNumeric(ExtractNumber(Rng.Value)) Then
            result = result + ExtractNumber(Rng.Value)
        End If
    Next Rng
    wSumExtractNumber = result
End Function

 

Outbound References

http://answers.microsoft.com/en-us/office/forum/office_2010-excel/how-do-i-create-a-number-format-for-a-cell-with/b307979f-9efa-4f14-89be-bb74d5223d66

Access Excel Function HKID Check Digit (last digit)

This Excel tutorial explains the algorithm of HKID Check Digit (last digit) and provide a custom Access Excel VBA Function to verify the Check Digit. (香港身份証最後號碼)

You may also want to read:

Access Excel Generate random HKID Hong Kong ID card number

HKID Check Digit

HKID_check_digit

Hong Kong ID card number has a last digit with bracket called “Check Digit“. Check Digit is a number to verify if the previous number and alphabet are correct. By understanding the algorithm of calculating Check Digit, you can generate a random HKID.

There are two main purposes for understand HKID Check Digit.

First, some online services only offer to local residents, they do not want overseas residents to register their service, therefore in the membership registration page, they ask you to enter a valid HKID number. The verification system cannot check whether the HKID is real, they only check if your Check Digit is valid.

Second, this checking can be used to verify if the employee database maintains correct records, or check before inputting the data in the system.

Algorithm of HKID Check Digit

There are two types of HKID number:

1) Prefix with one alphabet, such as  A123456(7)

2) Prefix with two alphabets, such as AB123456(7)

I will demonstrate the algorithm below using HKID A123456(x)

Step 1

Convert the prefix alphabet to a numeric value. If Prefix contains two alphabets, add 8 to the original converted value of single alphabet, regardless of the first alphabet.

For example, A should convert to 8, then AA (or BA,CA,DA, etc) should be converted to 8+8 = 16

In our example HKID A123456(x), the result is 8

Prefix AlphabetConverted value
A8
B16
C24
D32
E40
F48
G56
H64
I72
J80
K88
L96
M104
N112
O120
P128
Q136
R144
S152
T160
U168
V176
W184
X192
Y200
Z208
xA16
xB24
xC32
xD40
xE48
xF56
xG64
xH72
xI80
xJ88
xK96
xL104
xM112
xN120
xO128
xP136
xQ144
xR152
xS160
xT168
xU176
xV184
xW192
xX200
xY208
xZ216

Step 2

Convert each HKID digit to a number.

Nth HKID digitmultiplier
1st7
2nd6
3rd5
4th4
5th3
6th2

In our example HKID A123456(x)

1 is the 1st digit, multiply 1 by 7 = 7

2 is the 2nd digit, multiply 2 by 6 = 12

3 x 5 = 15

4 x 4 = 16

5 x 3 = 15

6 x 2 = 12

Total =  77

Step 3

Calculate remainder of (Step 1 result + Step 2 result)/11

= (8+77)/11

= 8

Step 4

Check Digit = 11 – result of Step 3

= 11 – 8

= 3

Step 5

The Check Digit should contain only a single digit, otherwise further convert using the below rules.

If Check Digit = 10, convert to A

If Check Digit = 11, convert to 0

Result

Since the calculated Check Digit is a single digit, x=3 for HKID A123456(x)

Custom VBA Function – HKID Check Digit

The manual calculation of Check Digit is very complicated, therefore I created a custom Function for Excel and Access for checking if the last digit is correct.

This Function removes all brackets and capitalize all alphabets during the checking (the original value will not be modified).

After the Function calculates a Check Digit, it will compare with the Check Digit of user input.

This Function returns TRUE if last digit is correct, FALSE if incorrect.

I have verified the accuracy of this custom Function with 40,000+ real HKID.

VBA Code – HKID Check Digit

Public Function wCheckHKID(ID As String) As String
    Dim newIDArr() As Variant
    newID = UCase(Replace(Replace(ID, "(", ""), ")", ""))
    lenNewID = Len(newID)
    IDnoDigit = Left(newID, lenNewID - 1)
    lenIDnoDigit = Len(IDnoDigit)
    For i = 1 To lenIDnoDigit
        ReDim Preserve newIDArr(i)
        newIDArr(i) = Mid(IDnoDigit, i, 1)
    Next i
    If lenIDnoDigit = 7 Then
        checkSum = (Asc(newIDArr(1)) - 64) * 8 + newIDArr(2) * 7 + newIDArr(3) * 6 + newIDArr(4) * 5 + newIDArr(5) * 4 + newIDArr(6) * 3 + newIDArr(7) * 2
        checkDigit = 11 - checkSum Mod 11
    ElseIf lenIDnoDigit = 8 Then
        checkSum = 6 + (Asc(newIDArr(2)) - 64) * 8 + newIDArr(3) * 7 + newIDArr(4) * 6 + newIDArr(5) * 5 + newIDArr(6) * 4 + newIDArr(7) * 3 + newIDArr(8) * 2
        checkDigit = 11 - checkSum Mod 11
    End If
    If checkDigit = 10 Then
        newCheckdigit = "A"
    ElseIf checkDigit = 11 Then
        newCheckdigit = "0"
    Else: newCheckdigit = checkDigit
    End If
    If Asc(newCheckdigit) = Asc(Right(newID, 1)) Then
        wCheckHKID = True
    Else
        wCheckHKID = False
    End If
End Function

Syntax of custom Access Excel Function – HKID Check Digit

wCheckHKID (ID)
IDFull HKID such as Z123456(2), accept values with or without brackets, lower case or upper case

Example of Custom Function – HKID Check Digit

hkid 11

Outbound References

http://www.techonthenet.com/excel/formulas/asc.php

Access Round Function and custom Round Function

This tutorial explains how to use Access Round Function (round to even logic) and create a custom Round Function to simulate Excel Round Function.

You may also want to read:

VBA Excel Access roundup rounddown Function

Excel Access MRound custom Function round to nearest multiple

Access Round Function – Round to even logic

Access Round Function is completely different from Excel Round Function.

For Excel Round Function, if decimal part is >=0.5, the integer rounds up, otherwise the integer rounds down.

For Access Round Function, as well as Access VBA, Excel VBA, the Round Function uses “Round to even” logic. Integer rounds up if decimal part >=0.6, round down if <=0.4. For case decimal part exactly =0.5, , then round down, otherwise round up(round up to even integer), same logic applies to negative number (See example).

I summarize the Access round to even logic below.

If decimal part >=0.6 Then
   Round up
ElseIf decimal part <=0.4 Then
   Round down
ElseIf decimal part = 0.5 Then
   If integer part is even number Then
        Round down
   ElseIf integer part is odd number Then
        Round up
  End If
End If

Round to even logic has other names:

-unbiased rounding

-convergent rounding

-statistician’s rounding

-Dutch rounding

-Gaussian rounding

-odd-even rounding

-bankers’ rounding

-broken rounding

Syntax of Access Round Function – Round to even logic

Round ( expression, [ decimal_places ] )

If [decimal_places] is omitted, default is 0 (round to integer)

Example of Access Round Function – Round to even logic

Round([Number],0)
NumberAccess RoundExcel RoundCheck Diff
0.100
0.200
0.300
0.400
0.501integer part is even number, round down
0.611
0.711
0.811
0.911
111
1.111
1.211
1.311
1.411
1.522integer part is odd number, round up
1.622
1.722
1.822
1.922
222
2.122
2.222
2.322
2.422
2.523integer part is even number, round down
2.633
2.733
2.833
2.933
333
3.133
3.233
3.333
3.433
3.544integer part is odd number, round up
3.644
3.744
3.844
3.944
444
4.144
4.244
4.344
4.444
-4.545integer part is even number, round down
-4.655
-4.755
-4.855
-4.955
-555
-5.155
-5.255
-5.355
-5.455
-5.566integer part is odd number, round up

VBA Code of custom Access Round Function – simulate Excel Round function

Some custom Round Function you can find on the Internet do not consider cases for negative number , but this one does.

Function wRound(pValue As Double, digit) As Double
    Dim ExpandedValue
    Dim IntPart As Long
    Dim FractionPart As Double
    Dim negNumber As Boolean
    If pValue < 0 Then
        pValue = 0 - pValue
        negNumber = True
    End If
    
    ExpandedValue = pValue * (10 ^ digit) 'Retrieve integer part of the number
    IntPart = Int(ExpandedValue)
    FractionPart = ExpandedValue - IntPart 'Retrieve the fraction part of the number
    If FractionPart < 0.5 Then
        result = IntPart / 10 ^ digit
    ElseIf FractionPart >= 0.5 Then
        result = (IntPart + 1) / 10 ^ digit
    End If
    
    If negNumber = True Then
        wRound = 0 - result
    Else
        wRound = result
    End If
End Function

Syntax of custom Access Round Function – simulate Excel Round function

wRound(pValue, digit)
pValuethe decimal value you want to convert
digitthe number of decimal places you want to convert to

 

Outbound References

http://www.techonthenet.com/access/functions/numeric/round.php

Custom VBA Excel Access Networkdays Function

This tutorial explains how to create a custom Excel Access Networkdays Function to simulate Excel Networkdays Function, exclude holiday and weekend

Why do we need Access Networkdays Function?

As of Access 2013 version, there is no Access Networkdays Function available, the function is only available in Excel all versions.

In Excel , Networkdays Function is used to calculate the number of “net working days” between two days, excluding Saturday and Sunday, and include both start date and end date in the calculation. Excel Networkdays also allows you to define a holiday list in worksheet to exclude from the net working days.

The syntax of Excel Networkdays is as below

NETWORKDAYS( start_date, end_date, [holidays] )

To understand how Excel Networkdays work, you can refer to the below link

Excel worksheet Networkdays function

Create a custom Excel Access Networkdays Function

In Excel Networkdays, [holiday] is a parameter that takes Range or Array. Since it is not possible select a range in Access as Excel does, I am moving the definition of holiday inside the code (highlighted in red)

Public Function wNetworkdays(beginDt As Date, endDt As Date) As Integer
    Dim publicHoliday() As Variant
    Dim tempDt As Date
    Dim count As Integer
    tempDt = beginDt
    publicHoliday() = Array(#1/1/2015#, #1/2/2015#)  'VBA Date format is in mm/dd/yyyy, remove the example dates if needed
    For i = 1 To DateDiff("d", beginDt, endDt)
        tempDt = DateAdd("d", 1, tempDt)
        If Weekday(tempDt, 2) = 6 Or Weekday(tempDt, 2) = 7 Then  'Define your scheduled day off, you can define weekday instead of weekend
            count = count + 1
        End If
    Next i
    For j = 0 To UBound(publicHoliday())
        If Weekday(publicHoliday(j), 2) <> 6 And Weekday(publicHoliday(j), 2) <> 7 And publicHoliday(j) >= beginDt And publicHoliday(j) <= endDt Then
            count = count + 1
        End If
    Next j
    wNetworkdays = DateDiff("d", beginDt, endDt) + 1 - count
End Function

Algorithm of wNetworkdays

– Define array publicHoliday() which stores holiday dates

– Use DateDiff() Function to count total number of days between start date and end date

– Use Weekday() Function to count total number of Saturday and Sunday between start date and end date

– Loop through publicHoliday() to further subtract number of public holiday which is not Saturday and Sunday

– Subtract number of weekend and holiday from total number of days

Syntax of custom Access Networkdays Function

wNetworkdays(beginDt, endDt)
beginDtThe start date of calculation period
endDtThe end date of calculation period

Both begin date and end date inclusive in the returned networkdays.

 Outbound References

http://msdn.microsoft.com/en-us/library/bb239428%28v=office.12%29.aspx