# Summing up digits in an integer

• October 14th, 2012, 07:18 AM
Taewo
Summing up digits in an integer
I'm a 50 year old trying to learn Visual Basic. I need help as follows:

I want to write a macro to check which integer from 100 to 999 has its sum of digits divisible by 3

e.g.435 = 4+3+5 = 12 and 12 is divisible by 3.

• October 14th, 2012, 09:18 AM
DataMiser
Re: Summing up digits in an integer
By your use of the word macro I assume that you are using VBA within one of the office products. It may help to know which one you are using.

As for the question you could use MID\$() to pull each digit from the number in question
You can then add the numbers together
You can use the MOD operator to see if the sum is evenly divisible by a given number.
• October 14th, 2012, 09:37 AM
Peter_B
Re: Summing up digits in an integer
For any number (expressed in base 10), if the number is divisible by 3 then so is the sum of the digits - and vice versa. So you could simply determine whether the number itself is divisible by 3.
• October 14th, 2012, 12:29 PM
DataMiser
Re: Summing up digits in an integer
I was thinking that may be the case as well but did not go so far as to confirm if so then it is as simple as just using a mod operator

Code:

```If MyNumber Mod 3 = 0 Then     MsgBox "Is evenly divisible" Else     MsgBox "Is not evenly divisible" End If```
• October 14th, 2012, 01:19 PM
Taewo
Re: Summing up digits in an integer
DataMiser, Thanks for your prompt response. I'm using VBA Excel 2010.
• October 14th, 2012, 01:36 PM
Taewo
Re: Summing up digits in an integer
DataMister, your code works. thanks a lot. regards.
• October 16th, 2012, 08:44 AM
HanneSThEGreaT
Re: Summing up digits in an integer