How to change case of matching letter with a VBA regex Replace?

前端 未结 2 1958
余生分开走
余生分开走 2021-01-25 01:40

I have a column of lists of codes like the following.

2.A.B, 1.C.D, A.21.C.D, 1.C.D.11.C.D
6.A.A.5.F.A, 2.B.C.H.1
8.ABC.         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-25 01:47

    Here is a workaround that uses the properties of each individual regex match to make the VBA Replace() function replace only the text from the match and nothing else.

    Sub fixBlah2()
    Dim re As VBScript_RegExp_55.RegExp, Matches As VBScript_RegExp_55.MatchCollection
    Dim M As VBScript_RegExp_55.Match
    Dim tmpChr As String, pre As String, i As Integer
    Set re = New VBScript_RegExp_55.RegExp
    re.Global = True
    re.Pattern = "\b([1-5]\.[A-Z])\.([A-Z])\b"
    For Each c In Selection.Cells
        'Count of number of replacements made. This is used to adjust M.FirstIndex
        '    so that it still matches correct substring even after substitutions.
        i = 0
        Set Matches = re.Execute(c.Value)
        For Each M In Matches
            tmpChr = LCase(M.SubMatches.Item(1))
            If M.FirstIndex > 0 Then
                pre = Left(c.Value, M.FirstIndex - i)
            Else
                pre = ""
            End If
            c.Value = pre & Replace(c.Value, M.Value, M.SubMatches.Item(0) & tmpChr, _ 
                      M.FirstIndex + 1 - i, 1)
            i = i + 1
        Next M
    Next c
    End Sub
    

    For reasons I don't quite understand, if you specify a start index in Replace(), the output starts at that index as well, so the pre variable is used to capture the first part of the string that gets clipped off by the Replace function.

提交回复
热议问题