简体   繁体   English

如何在一个单元格中从字符串中查找和添加数字

[英]How Can I Find and Add Numbers from a String in One Cell

Can someone help with adding the numeric values in an alphanumeric cell? 有人可以帮助在字母数字单元格中添加数字值吗?

For example, 例如,

Function onlyDigits(s As String) As String
'Variables needed (remember to use "option explicit").   '
Dim retval As String    ' This is the return string.      '
Dim i As Integer        ' Counter for character position. '

' Initialise return string to empty                       '
retval = ""

' For every character in input string, copy digits to     '
'   return string.                                        '
For i = 1 To Len(s)
    If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
        retval = retval + Mid(s, i, 1)
    End If
Next

' Then return the return string.                          '
onlyDigits = retval
End Function

Results: 结果:

Dim myStr as String myStr = onlyDigits ("3d1fgd4g1dg5d9gdg") MsgBox (myStr)

314159 gives a sum of 23! 314159的总和为23!

I would do this: 我会这样做:

Function SumOnlyDigits(s As String) As Long
    Dim Total As Long, i As Long

    For i = 1 To Len(s)
        If IsNumeric(Mid(s, i, 1)) Then Total = Total + CLng(Mid(s, i, 1))
    Next

    SumOnlyDigits = Total
End Function

Changed to return the total as Long instead of String. 更改为将总计返回为Long而不是String。

UPDATE: This will sum consecutive numbers mixed inside alphabets 更新:这将求和连续混合在字母表中的数字

Private Function SumOnlyNumbers(s As String) As Long
    Dim Total As Long, i As Long, x As Long

    i = 1
    Do Until i > Len(s)
        If IsNumeric(Mid(s, i, 1)) Then
            x = CLng(GetNumber(Mid(s, i)))
            Total = Total + x
            i = i + Len(CStr(x))
        Else
            i = i + 1
        End If
    Loop
    SumOnlyNumbers = Total
End Function

Private Function GetNumber(s As String) As String
    Dim sTmp As String, i As Long

    sTmp = ""
    For i = 1 To Len(s)
        ' Join characters until non numeric
        If IsNumeric(Mid(s, i, 1)) Then
            sTmp = sTmp & Mid(s, i, 1)
        Else
            Exit For
        End If
    Next
    GetNumber = sTmp
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM