【问题标题】:Extract substring from a string in VBA从VBA中的字符串中提取子字符串
【发布时间】:2012-06-21 14:58:01
【问题描述】:

我正在寻找编写一些 VBA 代码来从以下带有括号和连字符的字符串中获取以下信息,即

ACOST 2012 定价表 -(PRJ 216664 - 金融服务器退役)- 12 个月期限

使用 VBA for Excel 2007,我需要在这个字符串中获取以下两位并分配给两个不同的变量,即:

  • 216664
  • 金融服务器退役

我尝试了Mid() 语法,但无法提取这两个信息。

【问题讨论】:

  • 格式是否总是这样,即 (xxx xxxxxx - xxxxxxxxxxxxx)
  • SO 上已经存在许多相关问题。例如:hereherehere
  • @Siddharth Rout - 是的,格式将始终采用这种方式。

标签: vba excel excel-2007 substring


【解决方案1】:

如果格式保持不变,那么你可以使用这个

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

【讨论】:

    【解决方案2】:

    另一种方式;

    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
    

    获取“-(”之后的最后一组数字,在“-”之前 空格然后将所有内容移至下一个),然后是 空格或行尾"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2018-09-29
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多