How do you format text/strings in VBA?

偶尔善良 提交于 2019-12-06 14:17:53

You can't add anything to the string directly to make the cell have bold characters.

Once you've written the string out to the cell, you'll need to go back and reprocess the cell. For example:

With ActiveCell.Characters(Start:=11, Length:=6).Font 
    .Name = "Arial" 
    .FontStyle = "Bold" 
    .Size = 10 
    .Strikethrough = False 
    .Superscript = False 
    .Subscript = False 
    .OutlineFont = False 
    .Shadow = False 
    .Underline = xlUnderlineStyleNone 
    .ColorIndex = xlAutomatic 
End With 

This snippet will set only a portion of the cell to bold.

EDIT:

This code could be used to implement the above and give you what you want. It could be written better, but should give you an idea of what you've got to write:

Public Sub FormatOuput()

    Dim i As Integer

    'Format Task_name
    i = InStr(1, ActiveCell.Text, vbLf)
    MakeBold 1, i

    'Format 'Lead'
    MakeBold i + 1, 4

    'Format 'Ambassadors'
    i = InStr(i + 1, ActiveCell.Text, vbLf)
    MakeBold i+1, 11

    'Format 'Instructions'
    i = InStr(i + 1, ActiveCell.Text, vbLf)
    MakeBold i+1, 10

End Sub

Public Sub MakeBold(startPos As Integer, charCount As Integer)
    With ActiveCell.Characters(start:=startPos, length:=charCount).Font
        .Name = "Arial"
        .FontStyle = "Bold"
        .Size = 10
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ColorIndex = xlAutomatic
    End With
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!