使用 Font.Characters 设置 Excel 单元格内文本的格式

问题描述 投票:0回答:1

我正在尝试设置 Excel 单元格内文本的格式。

使用“字符”属性,我指定文本中要设为粗体的一小部分字符。

整个文本,从我的字符范围中的第一个字符到文本结尾都被设为粗体。

Private Sub TestFormatting()

    Dim TSheet As Worksheet
    Set TSheet = Worksheets("Test")
    
    TSheet.Cells(5, 1) = "This is some text" & vbLf & "This is some more text"
    
    With TSheet.Cells(5, 1)
        For i = 3 To 5
            .Characters(i).Font.Bold = True
        Next i
    End With
    
End Sub

结果是:
这是一些文字 这是更多文字

我只要求第3到5个字符加粗。

将代码更改为:

Private Sub TestFormatting() Dim TSheet As Worksheet Set TSheet = Worksheets("Test") TSheet.Cells(5, 1) = "This is some text" & vbLf & "This is some more text" With TSheet.Cells(5, 1) For i = 3 To 5 .Characters(i).Font.Bold = True Next i For i = 30 To 32 .Characters(i).Font.Bold = False Next i End With End Sub
结果是:

这是一些文字
这是一些更多文字
在这两种情况下,更改都会应用于从 For 循环中的第一个字符到文本末尾的整个文本,忽略我只想格式化 3 个字符。

excel vba formatting character cell
1个回答
1
投票
使用Characters (start, length),其中start是起始字符数,length是字符数

: TSheet.Cells(5, 1).Characters(3, 3).Font.Bold = True

© www.soinside.com 2019 - 2024. All rights reserved.