John said:
Assuming that the field is a Long Integer (smaller than two billion
odd), you
could use this little VBA function:
Public Function DigitSum(lngI As Long) As Long
DigitSum = 0
Do Until lngI = 0
DigitSum = DigitSum + lngI MOD 10
lngI = lngI \ 10
Loop
End Function
You'ld just use a calculated field in your query by typing
DigitSum: DigitSum(NumField)
in a vacant Field cell.
I thought a while about how to do it without code in a query, and it's
possible but would be pretty snarky!
VBA:
Note: A recursive function is shown just to be different.
Public Function SumOfDigits(lngX As Long) As Integer
If lngX < 10 Then
SumOfDigits = lngX
Else
SumOfDigits = SumOfDigits(lngX \ 10) + SumOfDigits(lngX Mod 10)
End If
End Function
SQL:
tblSumDigits
SDID AutoNumber
SumDigits Text
SDID SumDigits
1 220301200
2 200300
tblI
ID AutoNumber
I Long
ID I
1 1
2 2
...
18 18
qryPrettySnarky:
SELECT SDID, Sum(Val(Mid([SumDigits], I, 1))) AS SumOfDigits FROM
tblSumDigits, tblI GROUP BY SDID;
!qryPrettySnarky:
SDID SumOfDigits
1 10
2 5
Note: Having a Long value for tblSumDigits.SumDigits instead of text can
be used with the expression Sum(Val(Mid(CStr([SumDigits]), I, 1)))
James A. Fortune
(e-mail address removed)