将文本字符串中的数字相乘。 +综述

时间:2014-10-02 13:12:58

标签: excel excel-vba vba

概述:

A1 = Dog_dkp_1,Cat_dkp_50,Mouse_dkp_20

= Nmult(A1,3)

将单元格A1中的数字乘以3。 你得到:

Dog_dkp_3,Cat_dkp_150,Mouse_dkp_60

我可以使用可选的roundup参数。

= Nmult(A1,1.1,0)

= Nmult(目标,乘数,总结到点)

结果:Dog_dkp_2,Cat_dkp_55,Mouse_dkp_22

......开始时不是我的......

  

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
     

结束功能

1 个答案:

答案 0 :(得分:2)

只需要进行一些小改动即可。我在函数定义中添加了一个选项变量,并在计算中添加了RoundUp函数。

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

测试:( B列显示相邻A列单元格中的公式

enter image description here


修改

CLng为结果添加了一个前导空格。删除它的一种方法是修剪字符串。改变这一行:

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

对此:

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