如何根据VBA中的内容更改单元格

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

我的目标是删除这些单元格中的所有数字,所以我可以使用这些数字进行进一步的计算。 我在不同的网站上发现了很多类似的问题,但是这些问题很具体,我还是不明白怎么做。

所以问题是如何根据内容使用更改单元格或甚至一系列单元格? 我有一些想法如何使用string函数replace。 但没有什么看起来不错。

谢谢!

一个小function

 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 

另一种使用RegExp的方式

添加引用

添加对Microsoft VBScript正则expression式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