Home » excel » excel – Multiply numbers in / within text strings. +Roundup

excel – Multiply numbers in / within text strings. +Roundup

Posted by: admin April 23, 2020 Leave a comment

Questions:

Overview:

A1 = Dog_dkp_1,Cat_dkp_50,Mouse_dkp_20

=Nmult(A1,3)

Multiplies the numbers in cell A1 by 3.
And you get:

Dog_dkp_3,Cat_dkp_150,Mouse_dkp_60

I could use an optional roundup parameter.

=Nmult(A1,1.1,0)

=Nmult ( target, multiplier, roundup to point )

Results in : Dog_dkp_2,Cat_dkp_55,Mouse_dkp_22

… Its not mine to begin with…

Function Nmult(text As String, multiplier As Double)

Dim i As Long, char As String, numb As String
Application.Volatile True
For i = 1 To Len(text)
    char = Mid(text, i, 1)
    If char Like "#" Then
        While char Like "#"
            numb = numb + char
            i = i + 1
            char = Mid(text, i, 1)
        Wend
        char = Str((CLng(numb) * multiplier)) + char
        numb = Empty
    End If
    Nmult = Nmult + char
Next i

End Function

How to&Answers:

Just a couple small changes are needed for what you want. I added an option variable in the function definition and the RoundUp function in your calculation.

Function Nmult(text As String, multiplier As Double, Optional roundValue As Double)
    Dim i As Long, char As String, numb As String
    Application.Volatile True
    For i = 1 To Len(text)
        char = Mid(text, i, 1)
        If char Like "#" Then
            While char Like "#"
                numb = numb + char
                i = i + 1
                char = Mid(text, i, 1)
            Wend

            char = Str(Application.RoundUp((CLng(numb) * multiplier), roundValue)) + char
            numb = Empty
        End If
        Nmult = Nmult + char
    Next i
End Function

Tested: (Column B shows what formulas are in adjacent Column A cells

enter image description here


Edit

CLng adds a leading space to the result. One way to remove it is by trimming the string. Change this line:

char = Str(Application.RoundUp((CLng(numb) * multiplier), roundValue)) + char

To this:

char = LTrim$(Str(Application.RoundUp((CLng(numb) * multiplier), roundValue)) + char)