Get the value between the brackets

后端 未结 4 1752
感情败类
感情败类 2021-01-12 05:02

I have a column with some stuff that looks like the following string: V2397(+60)

How do I get the value between the brackets? In this case the +60

相关标签:
4条回答
  • 2021-01-12 05:39

    Use InStr to get the index of the open bracket character and of the close bracket character; then use Mid to retrieve the desired substring.

    Using InStr$ and Mid$ will perform better, if the parameters are not variants.

    0 讨论(0)
  • 2021-01-12 05:41

    I would use a regular expression for this as it easily handles

    • a no match case
    • multiple matches in one string if required
    • more complex matches if your parsing needs evolve

    The Test sub runs three sample string tests

    The code below uses a UDF which you could call directly in Excel as well, ie = GetParen(A10)

    Function GetParen(strIn As String) As String
        Dim objRegex As Object
        Dim objRegMC As Object
        Set objRegex = CreateObject("vbscript.regexp")
        With objRegex
            .Pattern = "\((.+?)\)"
            If .Test(strIn) Then
                Set objRegMC = .Execute(strIn)
                GetParen = objRegMC(0).submatches(0)
            Else
                GetParen = "No match"
            End If
        End With
        Set objRegex = Nothing
    End Function
    
    Sub Test()
    MsgBox GetParen("V2397(+60)")
    MsgBox GetParen("Not me")
    MsgBox GetParen(ActiveSheet.Range("A1"))
    End Sub
    
    0 讨论(0)
  • 2021-01-12 05:45

    VBA code:

    cellValue = "V2397(+60)"
    openingParen = instr(cellValue, "(")
    closingParen = instr(cellValue, ")")
    enclosedValue = mid(cellValue, openingParen+1, closingParen-openingParen-1)
    

    Obviously cellValue should be read from the cell.

    Alternatively, if cell A1 has one of these values, then the following formula can be used to extrcat the enclosed value to a different cell:

    =Mid(A1, Find("(", A1)+1, Find(")",A1)-Find("(",A1)-1)
    
    0 讨论(0)
  • 2021-01-12 06:00

    Thanks to Andrew Cooper for his answer.

    For anyone interested I refactored into a function...

     Private Function GetEnclosedValue(query As String, openingParen As String, closingParen As String) As String
        Dim pos1 As Long
        Dim pos2 As Long
    
        pos1 = InStr(query, openingParen)
        pos2 = InStr(query, closingParen)
    
        GetEnclosedValue = Mid(query, (pos1 + 1), (pos2 - pos1) - 1)
    End Function
    

    To use

    value = GetEnclosedValue("V2397(+60)", "(", ")" )
    
    0 讨论(0)
提交回复
热议问题