2

我有很多包含一些数字和其他不相关字符的单元格。例如,单元格可能看起来像:65f或 as 11,345asd

我的目标是删除这些单元格中除数字之外的所有内容,以便我可以使用这些数字进行进一步计算。我在不同的网站上发现了很多类似的问题,但它们非常具体,我仍然不明白如何正确地做到这一点。

所以问题是如何根据内容使用更改单元格甚至一系列单元格?我有一些想法如何使用字符串函数替换来做到这一点。但是没有什么好看的。

谢谢!

4

2 回答 2

9

使用正则表达式的另一种方法

添加参考

添加对Microsoft VBScript 正则表达式 5.5的引用。见下图

在此处输入图像描述

代码:将其粘贴到模块中

Option Explicit

Function GetNumbers(rng As Range) As Variant
    Dim StrSample As String
    Dim myRegExp As RegExp
    Dim myMatches As MatchCollection
    Dim myMatch As Match

    StrSample = rng.Value

    Set myRegExp = New RegExp

    With myRegExp
        .Pattern = "[^0-9]"
        .IgnoreCase = True
        .Global = True
    End With

    Set myMatches = myRegExp.Execute(StrSample)

    For Each myMatch In myMatches
      Debug.Print myMatch.Value
      StrSample = Replace(StrSample, myMatch.Value, "")
    Next
    GetNumbers = StrSample
End Function

屏幕截图

在此处输入图像描述

编辑

这是一个更短的版本,它根本不使用循环。

Function GetNumbers(rng As Range) As Variant
    Dim myRegExp As RegExp
    Set myRegExp = New RegExp
    myRegExp.Pattern = "[^0-9]"
    myRegExp.Global = True
    GetNumbers = myRegExp.Replace(rng.Value, "")
End Function
于 2012-09-21T10:33:55.923 回答
3

一个小功能

public function TONUM(str As string) As string
dim i As long
for i = 1 To len(str)
    if not mid$(str, i, 1) Like "[0-9]" then mid$(str, i, 1) = "?"
next
TONUM = replace$(str, "?", "")
end function
于 2012-09-21T10:39:56.867 回答