如何只用VBA格式化单元格中的一部分string

目标是将这些值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 

您需要指定单元格中的字符开头和长度,以便进行格式化:

因此,更换

 Cells(i, 2).Font.Color = RGB(0, 0, 255) 

 Cells(i, 2).Characters(Start:=outcomeNum, Length:=Len(seq)).Font.Color = RGB(0, 0, 255) 

只是因为我注意到:声明中缺lessseq

 Dim seq As Variant 

我build议使用Option Explicit来避免遗漏任何声明,并尽可能减less因variables名称中的拼写错误而导致的错误。