Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

excel - Bold text using RegExp Regular Expressions

I am trying to use regEx to find dates and bold them within text in multiple cells in a range but it appears that I am not using the correct expression for bolding text using regEx. The code below is working other than the bolding function. I need regEx as I need to bold all dates in the format of yyyy-mm-dd. I know that the regEx expression below is not correct to do this but i was going to get the bolding function working before i tackled the next part.

I have checked all the other questions and they all steer away from using regEx for bolding.

Sub Bold_a_date2()

Dim ws As Worksheets
Dim item As Variant
Dim arr As Variant
arr = Worksheets("Formatted").Range("M1:M1000")

Dim regEx As New RegExp
regEx.Global = True
regEx.Pattern = "202[0-9]"

Dim text As Variant
Dim mc As MatchCollection, row As Long
row = 1

  For Each text In arr
    
    If regEx.test(text) = True Then
    Set mc = regEx.Execute(text)
    
    Selection.Font.Bold = True
    Debug.Print text
        
    End If
    
row = row + 1

Next text


End Sub

enter image description here

question from:https://stackoverflow.com/questions/65929181/bold-text-using-regexp-regular-expressions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your data is a date value, the results will be weird. If the data is in text format, you can do as follows.

Sub Bold_a_date2()

Dim ws As Worksheets
Dim item As Variant
Dim arr As Range
Dim text As Range

Set arr = Worksheets("Formatted").Range("M1:M1000")
'Set arr = Worksheets("Formatted").Range("i1:i1000")

Dim regEx As New RegExp
regEx.Global = True
regEx.Pattern = "202[0-9]"


Dim mc As MatchCollection, row As Long
Dim m As Match
Dim s As Integer, l As Integer
    For Each text In arr
    
        If regEx.test(text) = True Then
            Set mc = regEx.Execute(text)
            For Each m In mc
                s = m.FirstIndex
                l = m.Length
                text.Characters(s + 1, l).Font.Bold = True
            Next m
            Debug.Print text
        End If
    Next text
End Sub

String vs Datevalue

enter image description here

multi case

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...