Excel VBA: How to remove substrings from a cell?

前端 未结 4 848
离开以前
离开以前 2021-01-06 08:01

I have a cell value like this:

This is a <\"string\">string, It should be <\"changed\">changed to <\"a\"> a number.

There

4条回答
  •  时光说笑
    2021-01-06 08:46

    Following up on the suggestion to use regular expressions, here's an example:

    Option Explicit
    
    Sub RemoveByRegexWithLateBinding()
    
        Dim strIn As String
        Dim strOut As String
        Dim objRegex As Object
    
        'input
        strIn = "This is a <""string"">string, It should be <""changed"">changed to <""a""> a number."
        Debug.Print "Input:" & vbCr & strIn
    
        'create and apply regex
        Set objRegex = CreateObject("VBScript.RegExp")
        objRegex.Pattern = "<""[^<>""]*"">"
        objRegex.Global = True
        strOut = objRegex.Replace(strIn, "")
    
        'test output
        Debug.Print "Output:" & vbCr & strOut
    
    End Sub
    

    Produces this output:

    Input:
    This is a <"string">string, It should be <"changed">changed to <"a"> a number.
    Output:
    This is a string, It should be changed to  a number.
    

    Diagram of regular expression:

    Which can be explained as finding a string that:

    • begins with <"
    • contains anything apart from the characters <, > and "
    • ends with ">

提交回复
热议问题