excel - 如何加粗字符串的某些文本部分

标签 excel vba

我在一个单元格中有一个字符串,我正在尝试加粗该字符串的某些部分。我有我的代码设置,所以每个案例都是该单元格中的一行。
第一个单元格是我开始的,下面的一个是我想要做的。以下是我到目前为止所拥有的代码。
enter image description here

Sub test()

            For Each cel In Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
             
                 Dim arr, line As Long, pos As Long, txt, length, dashPos
                 
                 arr = Split(cel.Value, Chr(10)) ' Spliting cell contents by newline character
                 
                 pos = 1
                 For line = 1 To UBound(arr) + 1
                     
                     txt = arr(line - 1)
                     length = Len(txt)
                 
                     'check which line we're on...
                     Select Case line
                         Case 4: 'Underline on line 4
                             cel.Characters(pos, length).Font.Underline = True
                         Case 5: 'Bold the team players
                            
                            
                         Case 6: 'Underline on line 6
                             cel.Characters(pos, length).Font.Underline = True
                     End Select
                 
                     pos = pos + Len(txt) + 1 'start position for next line
                 Next line
    
                Next cel
End Sub

最佳答案

由于您正在查找某个模式,我认为这可以通过正则表达式来完成,因为 MatchCollection2 中的每个匹配项对象将有一个起始索引,包括捕获模式的长度。让我们想象以下示例数据:
enter image description here
现在我们可以应用以下代码:

Sub Test()

Dim str As String: str = [A1]
Dim colMatch, objMatch

With CreateObject("vbscript.regexp")
    .Global = True
    .Pattern = "\S+:(?=.*$)"
    If .Test(str) = True Then
        Set colMatch = .Execute(str)
        For Each objMatch In colMatch
            Range("A1").Characters(objMatch.FirstIndex, objMatch.Length).Font.Bold = True
        Next
    End If
End With

End Sub
结果:
enter image description here

关于正则表达式的模式:
\S+:(?=.*$)
你可以看一个在线演示here以及下面的小分割:
  • \S+: - 1+ 非空白字符,包括冒号。
  • (?= - 积极的展望:
  • .*$ - 除了换行符之外的 0+ 个字符,直到结束字符串 anchor 。
  • ) - 关闭积极的前瞻。


  • 注:我们需要要么忘记正则表达式对象的“Newline”属性,要么将其值设置为FALSE。 .在我给出的示例中,我只是没有包含它,因为它将默认为 FALSE .如果将其设置为 true,则结束字符串 anchor 将不会简单地匹配整个字符串的结尾,而是每行的结尾(如果我们不想匹配“Server:”,这是我们想要避免的)。

    关于excel - 如何加粗字符串的某些文本部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65912765/

    相关文章:

    vba - VBA 下标超出范围

    excel - 将多个工作表中的数据合并到一个数组中

    excel - 从 Excel 到 Word 表格中的特定单元格

    vba - 将 Outlook 电子邮件回复作为任务收集并填充到 Excel 电子表格中

    excel - 连续取消保护表和保护表 2 次

    excel - 如何在Excel中将数字保存为字符串?

    python - 在 Excel 列中将文本与 URL 分开

    vba - 如何在 Excel 中查找单元格的所有依赖项(还有条件格式和数据验证)

    arrays - VBA:数组和全局变量声明

    vba - 在同一单元格的每一行之后添加文本