VBA How to use regular expression on a user input in a cell

前端 未结 1 1204
南笙
南笙 2021-01-29 06:34

I am trying to specify the user input in a cell with a regular expression. The idea is to use only these strings:

C1, C2, C3, C4, C5, C6, C7, C8, C9, C10


        
相关标签:
1条回答
  • 2021-01-29 07:15

    This code will check each set of three combinations when you update a cell. Paste the code in the worksheet rather than a module. It assumes your text follows the rule of:

    every 3 combinations must be separated with comma

    For example, the string C6 merge 1, C4 merge 1 will have C6 merge 1 and C4 merge 1 checked. It ignores the comma and leading/trailing spaces.

    Note: I haven't checked the RegExp pattern as that's not my forte, but it checks as you enter the data in column G. Maybe post a separate question to get the correct Reg Exp syntax?

    You may want to create the RegEx variable with a worksheet scope that gets initialised when the sheet is activated and destroyed when you leave the sheet (save having to do it each time you update a cell).

    Private Sub Worksheet_Change(ByVal Target As Range)
    
        Dim strPattern As String
        Dim regEx As RegExp
        Dim vValues As Variant
        Dim vValue As Variant
    
        If Not Intersect(Target, Range("G:G")) Is Nothing Then
            strPattern = "\b(C(?:10|[1-9])),(merge|complete framed|width),(\d+)"
            Set regEx = New RegExp
    
            vValues = Split(Target, ",")
    
            With regEx
                For Each vValue In vValues
                    '.Global = True 'Not needed as possible matches are passed one at a time using Split.
                    '.MultiLine = True
                    .IgnoreCase = False
                    .Pattern = strPattern
    
                    If .Test(Trim(vValue)) Then
                        MsgBox "Match found in " & Target.Value & " : " & Trim(vValue)
                    Else
                        MsgBox "No match"
                    End If
                Next vValue
            End With
        End If  
    
        Set regEx = Nothing
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题