简体   繁体   English

更改Excel单元格中多个子字符串的字体

[英]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 此值为X和Y,以及Z

I need to change the font only of X, Y, and Z. 我只需要更改X,Y和Z的字体。

Here is how I am currently changing the characters' font via vba: 这是我目前通过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 ☹ 此值为X和Y ,,

per suggestion of @TimWilliams via the comments, here's the solution that works: @TimWilliams通过评论的建议,这是可行的解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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