【问题标题】:Regexp & VBA - loop through cells, return matched value in adjacent cell [closed]正则表达式和 VBA - 遍历单元格,返回相邻单元格中的匹配值 [关闭]
【发布时间】:2017-05-17 19:36:18
【问题描述】:

如果在 A 列中,我的值如下 一个

A0394

948B0129

Zkjs333

0a0401a

09ab28

我想使用正则表达式和 VBA(不使用自定义函数)返回有 2 个字母后跟 2 个数字字符的匹配项 B

js33

ab28

代码会是什么样子?

【问题讨论】:

  • 为什么不先写出来呢?你有没有尝试过?
  • 我把它扔掉了,因为我运行不正常,而且我以前从未在 vba 中使用过正则表达式。这是我所拥有的sub test() Dim strPattern As String dim regex As Object, str as string set regex=createObject("VBScript.RegExp") with regex .pattern="[a-z]{2}[0-9]{2}" .global=true end with for each thing in range("A1:A4") set matches= regex.execute(thing) thing.offset(0,1)=regex.execute(thing) next

标签: regex vba excel for-loop


【解决方案1】:

你几乎拥有它。由于您只搜索一次出现的模式,比如说第一次,您可以将其设为matches(0),但首先使用matches.count 检查是否存在匹配项。

Sub Test()
  Dim cel As Range, matches As Object
  With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "[a-zA-Z]{2}[0-9]{2}"
    For Each cel In Range("A1:A10")
      Set matches = .Execute(cel.Value2)
      If matches.Count > 0 Then cel.Offset(0, 1).Value = matches(0)
    Next
  End With
End Sub

【讨论】:

    【解决方案2】:

    你的正则表达式是正确的,应该像这样在 VBA 中正确定义它

    Private Sub simpleRegex()
        Dim strPattern As String: strPattern = "[a-z]{2}[0-9]{2}"       
        Dim regEx As New RegExp      
    
    
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With
    

    regEx.Test(strInput)
    

    您可以检查字符串是否匹配。

    你可以找到一个很深的答案here

    【讨论】:

    • 使用示例 3 中的代码(循环范围)的非常深刻的答案:你会在 if 语句中写什么(if regex.test(strinput) then)来返回匹配的值成立?我尝试了 msgbox (regex.execute(strinput)) 但它返回错误:“参数数量错误或属性分配无效”
    • regex.execute(strinput) 返回所有可能的匹配项,我认为执行 `msgbox (regex.execute(strinput)) 您设置了太多参数。 @machump
    【解决方案3】:
    Sub test()
    
        Dim matches, regex As Object, c As Range
        Dim i As Long
    
        Set regex = CreateObject("VBScript.RegExp")
        With regex
            .Pattern = "[a-z]{2}[0-9]{2}"
            .Global = True
        End With
    
        For Each c In Range("A1:A4")
            Set matches = regex.Execute(c.Value)
    
            'if only one match expected...
            If matches.Count > 0 Then
                c.Offset(0, 1) = matches(0)
            End If
    
            'if can be multiple matches...
            'For i = 1 To matches.Count
            '    c.Offset(0, i) = matches(i - 1)
            'Next i
        Next
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2017-05-14
      • 1970-01-01
      相关资源
      最近更新 更多