简体   繁体   中英

Excel VBA - UDF text replace

I'm trying to replace any text in square brackets, including them – "[]" in a cell by emptiness with UDF:

Function RMV(iCell As Range) As Variant
RMV = Replace(iCell.Value, "[*]", "")
End Function

But I guess the asterisk ("*") does not work here.

To use reGex, you could use this as Function, remember to enable Microsoft VBScript Regular Expression 5.5

Function RMV(iCell As Range) As Variant
    Dim regEx As Object: Set regEx = CreateObject("VBScript.RegExp") 'If Error Set regEx  = New regexp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim strOutput As String

    strPattern = "\[\]|\[.+?\]|$"

    If strPattern <> "" Then
        strInput = CStr(iCell.Value)
        strReplace = ""

        With regEx
            .Global = True
            .MultiLine = False
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.test(strInput) Then
            RMV = regEx.Replace(strInput, strReplace)
        Else
            RMV = "Not matched"
        End If
    End If
End Function

Where the ReGex test uses the \\[\\]|\\[.+?\\]|$ expression. I am also new to Regex, so this expression can be optimized.

In sub procedure, that works.

Sub RMV(rng As Range)
rng.Replace "[*]", ""
End Sub

Sub Test()
RMV Range("A2")
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM