0 votes
in VBA by Expert (848 points)
Hello everyone

I have a text like that "Hello-World-Thanks" ..

Using split I can extract the first word Split(strName,"-")(0)

How can I color the second half of the extracted text?

So as in the example the extracted text is "Hello" >> 5 letters >> so 5 / 2 = 2.5 (rounded up to 3) so >> the letters "llo" should be colored

and at the same time keep all the text in the string

Simply the final result will be the same text "Hello-World-Thanks" with "llo" colored

1 Answer

+1 vote
by Skilled (466 points)
selected by
 
Best answer

Assuming you want to display the text in an Excel cell like A1, try this:

strName = "Hello-World-Thanks"
With ActiveSheet.Range("A1")
    .Font.ColorIndex = 1 ' black
    .Value = Split(strName, "-")(0)
    n = Len(.Value)
    k = n / 2
    .Characters((k + 1), (n - k + 1)).Font.ColorIndex = 3 ' red
End With

 

by Expert (848 points)
+1

Thanks a lot. You put the first word only and I need to put the whole text "Hello-World-Thanks" in A1 for example and color the letters "llo" only

I could fix it by editing the two lines

    .Value = strName
    n = Len(Split(strName, "-")(0))

Thank you very much for great help.

Best Regards

Welcome to wellsr Q&A
wellsr Q&A is the VBA and Python programming community that rewards you for learning how to code.

Getting Started
Register
VBA Cheat Sheets (On Sale Now)

Earn free prizes for asking VBA and Python questions and for answering questions asked by others in our community.

Looking for something else? Hire our professional VBA Help, instead.

What makes us different?
Our points system rewards you with a chance for free gifts based on the quality of your questions and answers. All you have to do is post and you could get rewarded, like these members:

ParserMonster $25 Amazon Gift Card
Hightree $10 Amazon Gift Card
Thales1 $10 Amazon Gift Card
runfunke $10 Amazon Gift Card
coolag $10 Amazon Gift Card
Siew Hun $10 Amazon Gift Card

So, why don't you join us? It really is an encouraging way to motivate members in our VBA and Python community.

Register

For more programming tips visit the VBA Tutorials Blog and the Python Tutorials Blog.

...