从单元格中删除字符

时间:2015-11-02 22:20:35

标签: excel excel-vba vba

此公式删除除数字以外的所有内容:

Sub qwerty()
    For Each r In Selection
        vout = ""
        v = r.Text
        n = Len(v)
        For i = 1 To n
            ch = Mid(v, i, 1)
            If ch Like "[0-9]" Then
                vout = vout & ch
            End If
        Next i
        r.Value = vout
    Next r
End Sub  

如何修改它以保持数字和小数点?

2 个答案:

答案 0 :(得分:0)

要加入.,请将其包含在Like表达式

If ch Like "[0-9.]" Then

答案 1 :(得分:0)

最好使用Regexp而不是通过初始范围循环缓慢循环逐个字符:

Sub Quicker()
Dim X
Dim ObjRegex As Object
Dim lngRow As Long
Dim lngCOl As Long

Set ObjRegex = CreateObject("vbscript.regexp")
ObjRegex.Global = True
ObjRegex.Pattern = "[^0-9/.]"

X = Selection.Value2
For lngRow = 1 To UBound(X, 1)
   For lngCOl = 1 To UBound(X, 2)
        X(lngRow, lngCOl) = ObjRegex.Replace(X(lngRow, lngCOl), vbNullString)
   Next
Next

Selection.Value2 = X

End Sub