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
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
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