excelvbaexcel-formulatext-parsingoffice-2007

How to sum the digits in text in a cell?


I have an Excel sheet
alt text

The requirement is to sum the digits in the cells in column 'C' and put the value in the corresponding cell in column 'B' (in my example 0.25 + 1 + 0.25 + 1 = 2.5).

The values in Column 'C' could change. The requirement is to update the value in 'B' as soon as the cell in column 'C' changes.

I did ask the creator to change to text and numbers in two different columns but that is not acceptable because of the standard template.


Solution

  • This can be achieved, without altering the text in the cell, using a Macro. I have to admit, the implementation will be a little retarded, since you need to do a few things.

    1 - Tokenize the entire cell content, and store the tokens into a string array.

    There is a problem already. The text located inside the cell is grossly inconsistent. You have -250 ms, - 250 ms, - 1sec, - 1 sec. Due to this, you are going to need to check for each instance. Therefore, you cannot just check if the value is a number, you need to check all the permutations that your team members have conveniently provided for you.

    The best way to do this would be to check against Regular Expressions. Therefore, #2 should be:

    2 - Check each value to see if it matches to one of many 4 Regular Expressions.

    3 - Depending on the Regex it matches with, extract the numerical value.

    a) If simply a value (ie->250), check if ms or sec proceeds the value. IF ms, divide the number by 1000. If sec, leave number as is. Add number to total.
    b) If a number preceded by a dash(-), remove dash, and repeat step a)
    c) If a number followed by letters, remove letters and repeat step a)
    d) If a number followed by a period, do nothing. This is a bullet point.