简体   繁体   中英

Change Font Of Multiple Sub Strings in Excel Cell

I have a font to show specific symbols. They are typed into the sheet with a standard/default font. I'm able to identify these characters and then change these characters' font to my symbol font, but having some trouble making it work correctly when there is more than one identified symbol in the cell.

For example and cell may contain:

This Value is X and Y, and Z

I need to change the font only of X, Y, and Z.

Here is how I am currently changing the characters' font via vba:

Sub InsertFont(insertRange As Range, symbolText As String, symbolPosition As Integer)
    Dim cellText As String
    Dim newValue As String
    cellText = insertRange.Value2
    newValue = Replace(cellText, symbolText, SymbolDict.Item(symbolText), 1, 1)
    insertRange.Value2 = newValue
    With insertRange.Characters(symbolPosition, Len(SymbolDict.Item(symbolText))).Font
        .Name = "MyFont"
    End With

End Sub

The problem is after each font change, the rest of the cell returns to the default font! How can I get the font changes to stick for all of the changes?

end result:

This Value is X and Y, and ☹

per suggestion of @TimWilliams via the comments, here's the solution that works:

Sub InsertSymbol(insertRange As Range, symbolText As String, symbolPosition As Integer)

    Dim cellText As String
    Dim newValue As String
    insertRange.Characters(symbolPosition, Len(symbolText)).Delete
    insertRange.Characters(symbolPosition, 0).Insert SymbolDict.Item(symbolText) '2nd parameter 0 to not overwrite any characters
    insertRange.Characters(symbolPosition, 1).Font.Name = "My Symbol Font Name"

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM