Extract Last Bracketed Characters from String in Excel VBA

元气小坏坏 提交于 2019-12-13 22:44:14

问题


My strings are filenames like this:

Sample Text (A12 V1.1)

Sample (V2) Text (A9 V2.3 8.99)

Sample Very Text (A34 8.3 V4)

How do I extract only the string starting with but excluding the 'V', contained within the last brackets only?

i.e. - 1.1, 2.3, 4


回答1:


Try this UDF

Function ExtractByRegex(sTxt As String)
With CreateObject("VBScript.RegExp")
    .Pattern = "V\d+(.)?(\d+)?"
    If .Test(sTxt) Then ExtractByRegex = .Execute(sTxt)(0).Value
End With
End Function

Update

Here's another version in which you can format the output

Sub Test_ExtractByRegex_UDF()
MsgBox ExtractByRegex("A9 V2.3 8.99")
End Sub

Function ExtractByRegex(sTxt As String)
With CreateObject("VBScript.RegExp")
    .Pattern = "V\d+(.)?(\d+)?"
    If .Test(sTxt) Then sTxt = Replace(.Execute(sTxt)(0).Value, "V", "")

    If Not InStr(sTxt, ".") Then sTxt = sTxt & "." & "000"
    ExtractByRegex = Split(sTxt, ".")(0) & IIf(InStr(sTxt, "."), ".", "") & Format(Split(sTxt, ".")(1), "000")
End With
End Function



回答2:


VBA's string functions can duplicate the results from a static pattern and you might want to return a true number if you are dropping the V prefix.

Option Explicit

Function ExtractWithoutRegex(sTxt As String)

    Dim b As Long, v As Long

    b = InStrRev(sTxt, "(")
    v = InStr(b, sTxt, "V")

    ExtractWithoutRegex = vbNullString

    If v > b Then
        sTxt = Mid$(sTxt, v + 1)
        sTxt = Split(sTxt)(0)
        ExtractWithoutRegex = Val(sTxt)
    End If

End Function


来源:https://stackoverflow.com/questions/56099989/extract-last-bracketed-characters-from-string-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!