简体   繁体   中英

Extract substring from a string in VBA

I am looking to write some VBA code to obtain the following pieces of information from the following string with brackets and hyphens, ie

ACOST 2012 Pricing Table - (PRJ 216664 - Financial Server Decommission) - 12 Month Term

Using VBA for Excel 2007, I need to obtain the following two bits within this string and assigned to two different variables, ie:

  • 216664
  • Financial Server Decommission

I tried the Mid() syntax but couldn't extract these two bits of info.

If the format is going to remain same then you can use this

Sub Sample()
    Dim strSample As String

    strSample = "ACOST 2012 Pricing Table - (PRJ 216664 - Financial Server Decommission) - 12 Month Term"
    strSample = Split(Split(strSample, "(")(1), ")")(0)

    Debug.Print Trim(Split(Split(strSample, "-")(0), " ")(1))
    Debug.Print Trim(Split(strSample, "-")(1))
End Sub

Another way;

Data = "ACOST 2012 Pricing Table - (PRJ 216664 - Financial Server Decommission) - 12 Month Term"

dim re As object, matches as object: Set re = createobject("vbscript.regexp")
re.pattern="- \(.*?(\d+)\s+-\s+(.*?)\)(\s|$)"

with re.Execute(Data)
    msgBox  .item(0).SubMatches(0) & " / " & .item(0).SubMatches(1)
End with

Get the last group of digits after "- (" before a "-" surrounded by whitespace then get everything upto the next ) thats followed by whitespace or the end of the line"

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