简体   繁体   中英

Remove text that is between two specific characters of a string

I have a column with data in the following format:

xxxx(yyyy)

I want to remove what is inside the parentheses, and the parentheses themselves.

I would use a regular expression for this job:

Sub DeleteMatches()
  Dim cell As Range, re As Object

  ' define the regular expression to match "(...)"  '
  Set re = CreateObject("VBScript.RegExp")
  re.Pattern = "\([^)]*\)"  ' matches "(...)"  '

  ' iterate and clean each cell in range "C2:C100"  '
  For Each cell In Range("C2:C100")
    cell.Value = re.Replace(cell.Value, Empty)
  Next

End Sub

You can readily cater for multiple replacements in one string with a Regexp

Sub Test()
Debug.Print CleanStr("xxxx(yyyy)")
Debug.Print CleanStr("and me ()")
Debug.Print CleanStr("and me ()` second string(aaa)")
End Sub

clean string

Function CleanStr(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
   .Pattern = "\([^)]*\)"
   .Global = True
   CleanStr = .Replace(strIn, vbNullString)
End With
End Function

尝试这个:

=LEFT(A1,FIND("(",A1)-1)

Select the cells you wish to process and run this short macro:

Sub DataGrabber()
    Dim r As Range
    For Each r In Intersect(ActiveSheet.UsedRange, Selection)
        If InStr(1, r.Value, "(") > 0 Then
            r.Value = Split(r.Value, "(")(0)
        End If
    Next r
End Sub
Dim x
x = Split("xxxx(yyyy)", "(")
Dim result
result = x(0)

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