从单元格中删除字母只留下数字

Remove letters from a cell leaving numbers only

我正在尝试删除单元格中的所有字母并保留剩余的数字。 我在这里找到了一些代码和其他问题,但 none 对我来说很有意义。

我在单元格 E23 "as12df34" 中,并希望单元格 E23 的值显示为“12 34”

任何人都可以帮助解决这个问题吗?

您可以使用正则表达式:

Sub UsageExample()
  Dim cl

  ' iterate each cell
  For Each cl in Range("Sheet1!A1:A100")
    ' replace each non digit sequence by a space
    cl.Value = ReplaceRe(cl.Value, "\D+", " ")
  Next

End Sub

Public Function ReplaceRe(text As String, pattern As String, replacement) As String
  Static re As Object
  If re Is Nothing Then
    Set re = CreateObject("VBScript.RegExp")
    re.Global = True
  End If
  re.pattern = pattern
  ReplaceRe = re.Replace(text, replacement)
End Function

如果你想做类似的事情,这里有一个 UDF。将 "Spaces" 设置为 True 或 False 将允许您在非数字字符所在的位置有一个 space。

Sub Test()
    Debug.Print Nums("as12df34", True)
End Sub

Function Nums(What As String, Spaces As Boolean) As String

Dim i As Long

For i = 1 To Len(What)

    If IsNumeric(Mid(What, i, 1)) = True Then Nums = Nums & Mid(What, i, 1)
    If IsNumeric(Mid(What, i, 1)) = False Then Nums = Nums & " "

Next i

Nums = Trim(Nums)

If Spaces = True Then
    Do Until InStr(Nums, "  ") = 0
        Nums = Replace(Nums, "  ", " ")
    Loop
Else
    Do Until InStr(Nums, " ") = 0
        Nums = Replace(Nums, " ", "")
    Loop
End If

End Function

我知道这可能已经得到解答,但我想让其他可能遇到这个问题的人看到另一种可能性。我想出了一个明显的解决方案来消除所有要替换的字母,只在单元格中留下数字。您只需将“”替换为“”即可留下字母留下的 space。

这是一个巨大的混乱,但我使用它并且它按预期工作,只需将函数拖到下一个单元格即可。无需打字。在我的情况下,我有一个像 "platinum ingot, 3" 这样的词,它将删除所有字母、逗号和 spaces 并留下 3 可用于计算内容。我用它在 1 个单元格中保存 2 个值,因为其中 1 个值永远不会包含数字。

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE( SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE( SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE( SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE( SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE( SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE( F5,"A",""),"B",""),"C",""),"D",""),"E",""),"F",""),"G",""),"H",""),"I",""),"J",""),"K",""),"L",""),"M",""),"N",""),"O",""),"P",""),"Q",""),"R",""),"S",""),"T",""),"U",""),"V",""),"W",""),"X",""),"Y",""),"Z",""),"a",""),"b",""),"c",""),"d",""),"e",""),"f",""),"g",""),"h",""),"i",""),"j",""),"k",""),"l",""),"m",""),"n",""),"o",""),"p",""),"q",""),"r",""),"s",""),"t","") ,"u",""),"v","") ,"w",""),"x",""),"y",""),"z",""),",","")," ","")