【问题标题】:VBA Excel - Extract each value surrounded by bracketsVBA Excel - 提取用括号括起来的每个值
【发布时间】:2012-10-01 03:19:30
【问题描述】:

我想提取括号内的值。

text = "{said} 和 {var2} 以及 {var3} 的人

openingParen = InStr(text, "{")
closingParen = InStr(text, "}")
enclosedValue = Mid(text, openingParen + 1, closingParen - openingParen - 1)

phrasevariable1.Value = enclosedValue
phrasevariable2.Value = enclosedValue
phrasevariable3.Value = enclosedValue

此代码仅适用于提取第一个值,有没有办法提取每个变量,并将它们相应地放入文本框 1 -> n

【问题讨论】:

    标签: excel vba extract


    【解决方案1】:

    您可以对未知数量的候选标记使用正则表达式;

    Dim matches As Object
    Dim Re As Object: Set Re = CreateObject("vbscript.regexp")
    Dim count As Long
    
    Re.Pattern = "{(.*?)}"
    Re.Global = True
    Set matches = Re.Execute("The man who {said} and also {var2} as well as {var3}")
    
    count = matches.count
    For i = 0 To count - 1
        MsgBox matches(i).submatches(0)
    Next
    

    (为Microsoft VBScript 正则表达式添加一个引用 以便提前绑定)

    【讨论】:

    • 当我尝试这个时它只返回一个匹配。是 Global = true 允许它返回多个匹配项吗?
    • 是的,如果我复制并粘贴,我会看到 3 个消息框
    • 我有类似的情况,除了我必须处理的字符串用]{括起来。我对正则表达式相当陌生 - 经过大量阅读后,我可以进行一些搜索,但我似乎无法为这两个分隔符找到正确的语法。
    • 方括号必须转义,因为它们作为正则表达式字符具有重要意义,因此请尝试"\[(.*?)\]"
    • 尝试"]([^\]]*?){" - 即从没有后续的]匹配]以防止[69]导致问题
    【解决方案2】:

    另一种允许任意数量匹配的方式:

    Const stri As String = "The man who {said} and also {var2} as well as {var3}"
    Dim sp
    
    sp = Filter(Split(Replace(Chr(13) & stri, "}", "{" & Chr(13)), "{"), Chr(13), False)
    

    【讨论】:

      【解决方案3】:

      假设你总是有三对括号中的文本,只需创建一个数组变量,然后在你的文本字符串上使用split 来获取值:

      Dim myArray
      myArray = Split(text, "{")
      
      phasevariable1.Value  = Left(myArray(1), InStr(myArray(1), "}") - 1)
      phasevariable2.Value  = Left(myArray(2), InStr(myArray(2), "}") - 1)
      phasevariable3.Value  = Left(myArray(3), InStr(myArray(3), "}") - 1)
      

      【讨论】:

        猜你喜欢
        • 2017-03-19
        • 2021-05-13
        • 1970-01-01
        • 2015-04-19
        • 2015-06-26
        • 2019-03-12
        • 2010-09-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多