Pattern match count in excel (regex & vba)

后端 未结 2 2025
一整个雨季
一整个雨季 2021-01-22 02:11

I have an Office 2007 .XLSX file containing over 5000 records like the below (a single cell with multiple rows of text). The issue: on an adjacent cell, put count

2条回答
  •  不思量自难忘°
    2021-01-22 02:38

    You can also include newlines in the Pattern expression by using \n. this way, you don't have to split the text in an array:

    Private Function String_CountRegExp_Debug()
    
        'Input of the test text
        Dim TestText As String
        TestText = "1/15/2013 1:30:11 AM Userx" & vbNewLine & _
                "Had to reboot system" & vbNewLine & _
                "1/15/2013 1:32:11 AM Userx" & vbNewLine & _
                "System running finished rebooting and appears to be working" & vbNewLine & _
                "11/15/2013 12:30:11 AM Userx" & vbNewLine & _
                "System hung again"
    
        'Input of the Pattern
        Dim RE_Pattern As String
        RE_Pattern = "(\d{1,2})\/(\d{1,2})\/(\d{4})\s(\d{1,2}):(\d{1,2}):(\d{1,2})\s([A,P]M).*\n"
    
        Debug.Print String_CountRegExp(TestText, RE_Pattern)
    
    End Function
    
    Public Function String_CountRegExp(Text As String, Pattern As String) As Long
    'Count the number of Pattern matches in a string.
    
        'Set up regular expression object
        Dim RE As New RegExp
        RE.Pattern = Pattern
        RE.Global = True
        RE.IgnoreCase = True
        RE.MultiLine = True
        'Retrieve all matches
        Dim Matches As MatchCollection
        Set Matches = RE.Execute(Text)
        'Return the corrected count of matches
        String_CountRegExp = Matches.Count
    
    End Function
    

提交回复
热议问题