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

gro*_*zhd 2 excel vba excel-vba

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

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

所以问题是如何根据内容使用变化细胞或甚至一系列细胞?我有一些想法如何使用字符串函数替换它.但没有什么看起来不错.

谢谢!

Sid*_*out 9

另一种使用RegExp的方法

添加参考

添加对Microsoft VBScript Regular Expressions 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
Run Code Online (Sandbox Code Playgroud)

屏幕截图:

在此输入图像描述

编辑

这是一个较短的版本,根本不使用循环.

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
Run Code Online (Sandbox Code Playgroud)