问题
I have a table with lots of word and need find words with capital letter and change its colour. For example:
A1: event
A2: Event
A3: Happy day
- and should change the colour of the words to red in A2 and A3 but in A3 just the "Happy" word. I tried to solve with conditional formatting but I failed. :) (Maybe VBA?)
Thanks for any help.
回答1:
I would probably skip the regex and just check against the ucase equivalent of the first character (this is just a guess, but I think it will be faster than using regex also). Like this:
Sub Capitalize()
Dim sheet As Worksheet
Dim cell, range As range
Dim results() As String
Dim pos As Integer
Set sheet = ActiveSheet
Set range = sheet.range("a1", sheet.range("a" & Rows.Count).End(xlUp))
For Each cell In range
pos = 1
results = Split(cell)
'if first char is upper then set color
For Each r In results
If Left(r, 1) = UCase(Left(r, 1)) Then
cell.Characters(pos, Len(r) + 1).Font.Color = vbRed
End If
pos = pos + Len(r) + 1
Next
Next
End Sub
回答2:
Reference - MicroSoft VBScript Regular Expressions X.X
Sub test()
Dim mCol As MatchCollection
Dim Ws As Worksheet
Dim rngDB As Range, rng As Range
Dim strPattern As String
Dim s As String
Dim i As Integer, Ln As Integer, c As Integer
Set Ws = ActiveSheet
Set rngDB = Ws.Range("a1", Ws.Range("a" & Rows.Count).End(xlUp))
strPattern = "[A-Z][a-z]{1,}"
For Each rng In rngDB
s = rng.Value
Set mCol = GetRegEx(s, strPattern)
If Not mCol Is Nothing Then
For i = 0 To mCol.Count - 1
c = mCol.Item(i).FirstIndex + 1
Ln = mCol.Item(i).Length
rng.Characters(c, Ln).Font.Color = vbRed
Next i
End If
Next
End Sub
Function GetRegEx(StrInput As String, strPattern As String) As Object
Dim RegEx As New RegExp
Set RegEx = New RegExp
With RegEx
.Global = True
.IgnoreCase = False
.MultiLine = True
.Pattern = strPattern
End With
If RegEx.test(StrInput) Then
Set GetRegEx = RegEx.Execute(StrInput)
End If
End Function
回答3:
edited Kevin's answer if you want to check any alphabet in the word (not just first) for uppercase and highlight it red if true
Sub Capitalize()
Dim sheet As Worksheet
Dim cell As range, myrange As range
Dim results() As String
Dim pos As Integer
Set sheet = ActiveSheet
Set myrange = sheet.range("a1", sheet.range("a" & Rows.Count).End(xlUp))
For Each cell In myrange
pos = 1
results = Split(cell)
For Each r In results
If r <> LCase(r) Then
cell.Characters(pos, Len(r) + 1).Font.Color = vbRed
End If
pos = pos + Len(r) + 1
Next
Next
End Sub
来源:https://stackoverflow.com/questions/60357683/change-colour-of-words-with-capital-letter