目标是将这些值 A10、B10、C10、D10、E10、F10、G10、H10、I10、J1 更改为字体蓝色。
例如,“Yonge St A10、B10”,只有 A10 和 B10 的字体颜色应为蓝色,而“Yonge St”将保持黑色。
我有一个VBA代码。但是,代码更改了单元格中的所有文本颜色,而不是应更改的特定文本。见下文:
Dim i As Long
Dim sequences As String
' The sequence contains the values to highlight
sequences = "A10,B10,C10,D10,E10,F10,G10,H10,I10,J1"
' Split sequence list, so it can loop through each value in the array
Dim seqList() As String
seqList = Split(sequences, ",")
' This loops through up to Row 20 to determine if the cell value contains a sequence value, if it does, then it highlights it blue
For i = 1 To 20
Dim cellVal As String
cellVal = Cells(i, 2).Value 'Cells (i, 2) --> i refers to row number and 2 refers to column number. So in this case I set it to B
For Each seq In seqList
Dim outcomeNum As Integer
outcomeNum = InStr(cellVal, seq)
If outcomeNum > 0 Then
Cells(i, 2).Font.Color = RGB(0, 0, 255) ' You can set the blue colour here or change it to something else
End If
Next seq
Next i
Run Code Online (Sandbox Code Playgroud)
您需要指定要格式化的单元格内的字符开始和长度:
因此更换
Cells(i, 2).Font.Color = RGB(0, 0, 255)
Run Code Online (Sandbox Code Playgroud)
和
Cells(i, 2).Characters(Start:=outcomeNum, Length:=Len(seq)).Font.Color = RGB(0, 0, 255)
Run Code Online (Sandbox Code Playgroud)
只是因为我注意到:seq声明中缺少。
Dim seq As Variant
Run Code Online (Sandbox Code Playgroud)
我建议使用Option Explicit以避免忘记任何声明并最大限度地减少由于变量名称中的拼写错误而导致的错误。
| 归档时间: |
|
| 查看次数: |
2982 次 |
| 最近记录: |