The DigitSum() Function

With the example for DigitSum(Number), we leave geometry behind for a short time and turn to arithmetic. This example explains the following:

  • How to use loops

  • How to use VBA functions

  • How to handle variables

To calculate the sum of the digits of a number, you add up the digits one by one:

  1. Add the first digit of the number to the subtotal (currently zero).

  2. Add the second digit of the number to the subtotal.

  3. Add the third digit of the number to the subtotal.

  4. Add the fourth digit of the number to the subtotal.

  5. Continue until the end of the number is reached.

All programming languages include elements that allow you to run tasks repeatedly. The generic term for this is a loop.

Programming Loops

VBA recognizes several loop types:

  • For...Next ...

Get Microsoft® Excel® 2010 Formulas & Functions Inside Out now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.