'How do I change font for each line in a cell if it starts with a special character?
I need to change font for each line in a multi-lined cell, if the line starts with "#" and "-".
My macro changes the font for the first instance of the special character and everything below it.
I need it to check if each line in a cell starts with the special character (i.e. # or -) and then change if true.
Dim i as Range
Dim POS As Long, Before As Long, After As Long
For Each i in Sheet(1).UsedRange.Columns(2).Cells
POS = 0
If InStr(1, i.text, "#") > 0 Then POS = InStr(1, i.text, "#")
If InStr(1, i.text, "-") > 0 Then POS = InStr(1, i.text, "-")
If POS > 0 Then
Before = InStrRev(i.text,chr(10), POS)
After = InStr(POS, i.text, vbNewline)
With i.Characters(Start:=Before + 1, Length:=After - (Before + 1).font
.Name = "Consolas"
.Size = 12
End With
End If
Next i
Solution 1:[1]
Here's one approach using split() to check each line individually:
Sub Tester()
Dim c As Range, arr, ln, n As Long, pos As Long
For Each c In Sheet1.UsedRange.Columns(2).Cells
If Len(c.Value) > 0 Then
arr = Split(c.Value, vbLf) 'get an array of lines
pos = 1 'start point
For n = 0 To UBound(arr) 'loop over the lines
ln = arr(n)
Debug.Print ln
' # must be escaped by wrapping in []
If Trim(ln) Like "-*" Or Trim(ln) Like "[#]*" Then
With c.Characters(Start:=pos, Length:=Len(ln)).Font
.Name = "Consolas"
.Size = 12
End With
End If
pos = pos + Len(ln) + 1 'move start point
Next n
End If 'has any value
Next c
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Williams |
