In this article, we will create a custom function to calculate the sum of digits in a cell.
Sample data for this example consists of sales data. Each agent has sold different product. In a cell we have count of item sold followed by the product name. We want to find the total item sold by each agent.
We have created “SumDigits” function to calculate the sum of digits in the cell. This function takes range of cell as input and returns the sum of digits in the cell.
We have created custom function “SumDigits” to calculate the sum of digits in a cell. In this function, we find the length of string in the cell and then loop from first character to the last character in the string. Then we find and add the numeric values found in the string to get the sum of digits.
Mid(Number, i, 1)
Mid function is used to extract the sub-string from the main string. Above code will extract one character from the main string at a time.
IsNumeric function is used to check whether the given value is numeric.
Val function is used to convert the string to numeric value.
Please follow below for the code
Option Explicit Function SumDigits(Number As Variant) Dim i As Integer For i = 1 To Len(Number) If IsNumeric(Mid(Number, i, 1)) Then SumDigits = SumDigits + Val(Mid(Number, i, 1)) End If Next i End Function
We would love to hear from you, do let us know how we can improve our work and make it better for you. Write to us at email@example.com
The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.