Question posted 2012 · +2 upvotes
I would like to write a VBA function to highlight specific text within an excel cell. Is this possible? I’ve been googling but it’s unclear at this point.
to clarify, I would like to search a specific column for a text value (actually a list of values) and highlight the matched text in say yellow.
Note: this is what I ended up doing:
Sub Colors()
Dim searchString As String
Dim targetString As String
Dim startPos As Integer
searchString = "abc"
targetString = Cells(2, 1).Value
startPos = InStr(targetString, searchString)
If startPos > 0 Then
Cells(2, 1).Characters(startPos, Len(searchString)).Font.Color = vbRed
End If
End Sub
Accepted answer +10 upvotes
This is the basic principle, I assume that customizing this code is not what you are asking (as no details about this were provided):
Sub Colors()
With Range("A1")
.Value = "Test"
.Characters(2, 2).Font.Color = vbGreen
End With
End Sub
Small description although it speaks quite for itself: the first “2” refers to the first character that needs to be colored, the second “2” refers to the length.
VBA Core objects referenced (3)
Font.Color— Change the Color of the Horizontal Axis of a SparklineRange— Refer to Cells by Using a Range ObjectRange— Delete Duplicate Entries in a Range
Top vba Q&A (6)
- Difference between Visual Basic 6.0 and VBA +122 (2009)
- VBA – how to conditionally skip a for loop iteration +116 (2011)
- VBA: Test if string begins with a string? +53 (2013)
- html parsing of cricinfo scorecards +47 (2012)
- Code to loop through all records in MS Access +46 (2011)
- Access VBA | How to replace parts of a string with another string +44 (2011)
vba solutions on this site
.