目标是将这些值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
答案 0 :(得分:3)
您需要在单元格中指定要格式化的字符开头和长度:
因此替换
Cells(i, 2).Font.Color = RGB(0, 0, 255)
与
Cells(i, 2).Characters(Start:=outcomeNum, Length:=Len(seq)).Font.Color = RGB(0, 0, 255)
因为我注意到:声明中缺少seq
。
Dim seq As Variant
我建议使用Option Explicit
以避免遗忘任何声明并最大限度地减少因变量名称中的拼写错误而导致的错误。