Excel VBA - 从字符串中删除除数字和点之外的所有内容

问题描述 投票:0回答:1

使用正则表达式从单元格中删除除数字和点之外的所有文本的代码的最佳方法是什么?

我在 Regex101 上得到了基本的正则表达式“[^.0-9]+)”,但我尝试的一些代码不起作用。

我在第一个代码上收到一个空的错误框,在第二个代码上收到“用户定义的类型未定义”。

第一个代码

Sub RegexDelete()

Dim text As String
Dim regEx As Object
Dim test As Object

text = activecell.value

Set regEx = CreateObject("VBScript.Regexp")

regEx.Global = True
regEx.Pattern = "[^.0-9]+)"

Set test = regEx.Execute(text)
MsgBox (test(0).Value)

End Sub

第二个代码

Sub simpleRegex()
    Dim strPattern As String: strPattern = "[^.0-9]+)"
    Dim strReplace As String: strReplace = ""
    Dim regEx As New RegExp
    Dim strInput As String
    Dim Myrange As Range
    
    Set Myrange = ActiveSheet.Range("A1")
    
    If strPattern <> "" Then
        strInput = Myrange.Value
        
        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With
        
        If regEx.test(strInput) Then
            MsgBox (regEx.Replace(strInput, strReplace))
        Else
            MsgBox ("Not matched")
        End If
    End If
End Sub
excel vba
1个回答
0
投票

请尝试一下。

Sub RegexDelete()
    
    Dim text As String
    Dim regEx As Object
    
    text = ActiveCell.Value
    
    Set regEx = CreateObject("VBScript.Regexp")
    
    regEx.Global = True
    regEx.Pattern = "[^.0-9]"
    
    MsgBox regEx.Replace(text, "")
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.