需要Excel UDF删除非数字字符

时间:2018-07-18 15:29:04

标签: excel excel-vba

我没有分类为非数字的清单。 请帮助

2 个答案:

答案 0 :(得分:1)

其中之一应该做。

Function keepNums(str As String)
    Static rgx As Object

    'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF
    If rgx Is Nothing Then
        Set rgx = CreateObject("VBScript.RegExp")
    End If
    keepNums = vbNullString

    With rgx
        .Global = True
        .MultiLine = True
        .Pattern = "[^0-9]"
        keepNums = .Replace(str, vbNullString)
    End With
End Function

Function delNums(str As String)
    Static rgx As Object

    'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF
    If rgx Is Nothing Then
        Set rgx = CreateObject("VBScript.RegExp")
    End If
    delNums = vbNullString

    With rgx
        .Global = True
        .MultiLine = True
        .Pattern = "[0-9]"
        delNums = .Replace(str, vbNullString)
    End With
End Function

答案 1 :(得分:1)

这都是例程,一个例程删除所有数字字符,另一个例程删除除数字字符之外的所有内容:

Function deleteNumeric(strSource As String) As String
    Dim delChar As Integer
    For delChar = 48 To 57 ' ASCII code 48 is '0', through to 57 for '9'
        strSource = Replace(strSource, Chr(delChar), "")
    Next
    deleteNumeric = strSource
End Function

Function keepNumeric(strSource As String) As String
    Dim indxChar As Long, eachChar As String
    For indxChar = 1 To Len(strSource)
        eachChar = Asc(Mid(strSource, indxChar, 1))
        If eachChar > 47 And eachChar <= 57 Then
        keepNumeric = keepNumeric & Chr(eachChar)
        End If
    Next
End Function
相关问题