Summing up digits in an integer
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: Summing up digits in an integer

Hybrid View

  1. #1
    Join Date
    Oct 2012
    Posts
    3

    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.

  2. #2
    DataMiser is offline Super Moderator Power Poster
    Join Date
    Jul 2008
    Location
    WV
    Posts
    4,838

    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.

  3. #3
    Join Date
    Oct 2012
    Posts
    3

    Re: Summing up digits in an integer

    DataMiser, Thanks for your prompt response. I'm using VBA Excel 2010.

  4. #4
    Join Date
    Jan 2009
    Posts
    596

    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.

  5. #5
    DataMiser is offline Super Moderator Power Poster
    Join Date
    Jul 2008
    Location
    WV
    Posts
    4,838

    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.

  6. #6
    Join Date
    Oct 2012
    Posts
    3

    Re: Summing up digits in an integer

    DataMister, your code works. thanks a lot. regards.

  7. #7
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,091

    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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center