Sunday, September 5, 2010

VB Script for checking division by 3 in Excell

The math rule is that if a sum of the digits of a number can be divided by 3 without remainder, than the number is self can be divided by 3 without remainder. I don't know if this has been proven, but I know for sure that it works. So if you calculate the sum of the digits of a number and it's 3, 6 or 9, you can be sure it can be divided by 3 without remainder. The function I wrote below just sums the digits recursively until there is a single digit. You can do the final if check on your own :D

Function DigitSum(txt As String) As String
    Dim rez As Long
    Dim srez As String
    rez = 0
    'tt = ""
    For i = 1 To Len(txt)
        k = Mid(txt, i, 1)
        'tt = tt & k
        j = CInt(k)
        rez = rez + j
    Next i
    srez = CStr(rez)
    While (Len(srez) > 1)
      srez = DigitSum(srez)
    Wend
    DigitSum = srez
End Function