-
October 14th, 2012, 07:18 AM
#1
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.
Thanks in advance for your assistance.
-
October 14th, 2012, 09:18 AM
#2
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.
Always use [code][/code] tags when posting code.
-
October 14th, 2012, 09:37 AM
#3
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
#4
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
Always use [code][/code] tags when posting code.
-
October 14th, 2012, 01:19 PM
#5
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
#6
Re: Summing up digits in an integer
DataMister, your code works. thanks a lot. regards.
-
October 16th, 2012, 08:44 AM
#7
Re: Summing up digits in an integer
Please mark your thread resolved if your issue has been solved.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|