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

时间:2013-09-02 23:13:19

标签: excel vba excel-vba

有人可以帮助在字母数字单元格中添加数值吗?

例如,

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

结果:

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

314159总和为23!

1 个答案:

答案 0 :(得分:0)

我会这样做:

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

更改为将总数返回为Long而非String。

更新: 这将在字母表中混合连续数字

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