[英]How to only format a part of a string in a cell with VBA
The goal is to change these values A10,B10,C10,D10,E10,F10,G10,H10,I10,J1 to a font blue color.目标是将这些值 A10、B10、C10、D10、E10、F10、G10、H10、I10、J1 更改为蓝色字体。
For example, "Yonge St A10, B10", only A10 and B10 should be in a blue font color, whereas "Yonge St" will remain black.例如,“Yonge St A10, B10”,只有 A10 和 B10 应为蓝色字体颜色,而“Yonge St”将保持黑色。
I have a VBA code.我有一个 VBA 代码。 However, the code changes all the text color in a cell, and not the specific text that should be changed.但是,代码更改了单元格中的所有文本颜色,而不是应该更改的特定文本。 See below:见下文:
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
You need to specify the character start and length within the cell, that you want to format:您需要在单元格中指定要格式化的字符开始和长度:
Therefore replace因此更换
Cells(i, 2).Font.Color = RGB(0, 0, 255)
with和
Cells(i, 2).Characters(Start:=outcomeNum, Length:=Len(seq)).Font.Color = RGB(0, 0, 255)
Just because I noticed: seq
is missing in declaration.只是因为我注意到:声明中缺少seq
。
Dim seq As Variant
I recommend using Option Explicit
to avoid forgetting any declarations and minimizing errors due to typos in variable names.我建议使用Option Explicit
以避免忘记任何声明并最大限度地减少由于变量名拼写错误而导致的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.