Regexp& VBA - 循环遍历单元格,返回相邻单元格中的匹配值

时间:2017-05-17 19:36:18

标签: regex vba excel-vba for-loop excel

如果在A栏中,我有类似的值 的 A

A0394

948B0129

Zkjs333

0a0401a

09ab28

我希望返回匹配,其中有2个alpha后跟2个数字字符,使用正则表达式和VBA(不使用自定义函数) 的

js33

AB28

代码会是什么样的?

3 个答案:

答案 0 :(得分:0)

你的正则表达式是正确的,应该这样在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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你几乎拥有它。由于您只搜索该模式的一次,例如第一次,您可以将其设为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