首页 > 解决方案 > 返回后格式化文本段和:在文本中

问题描述

我们有一系列文档需要格式化以获得更好的可见性。

作为我们语音到文本协议的输出,我们得到一个成绩单。

VBA 脚本应该在每个(返回)之后将文本格式化为粗体,并且 (:) 之后的文本在下一次返回之前不加粗。

示例:
扬声器 1 问题 1:回答 回答 回答
扬声器 1 问题 2:回答 回答 回答

在函数的第一部分,这并没有按预期工作。

Sub BoldGenerator()

    ' BoldGenerator Macro
    Selection.WholeStory

    'Make each .Method belong to Selection.Find for readability
    With Selection.Find
        'Set search criteria for break font
        .Text = "^l"
        'Find next occurrence
        .Execute
        
        Do While .Found
        Selection.Text = Selection.Font.Bold = True
        .Execute
        Loop
        
    End With
    
    '
    Call BoldGenerator
End Sub

标签: vbams-wordtext-formatting

解决方案


这应该加粗 (return)(实际上是换行符或回车)和冒号 (:) 之间的所有内容

这不是一个简单的 VBA。使用的正则表达式在 VBA 中不是本机的,因此我们需要从 VBScript 库中获取它们。我们使用正则表达式来查找从回车符开始并以冒号结束的所有实例。正则表达式无法更改格式(变为粗体)。所以我们也需要使用.Find方法。我们再次找到之前发现的内容,但这次我们将其设为粗体。

您会看到第一个实例不会变为粗体,因为它不会在回车后开始。

Sub BoldGenerator()

Dim RE As Object
Dim REMatches As Object
Dim mch As Object

Selection.HomeKey wdStory
Selection.WholeStory

Set RE = CreateObject("vbscript.regexp")
With RE
  .Global = True
  .Pattern = "\r(.+?:)"
End With
Set REMatches = RE.Execute(Selection.Text)

If REMatches.Count > 0 Then
  Selection.HomeKey wdStory
    With Selection.Find
      .ClearFormatting
      .Forward = True
      .Format = False
      .MatchCase = True
      For Each mch In REMatches
        .Text = mch
        .Execute
        Selection.Font.Bold = True
        Selection.MoveRight wdCharacter
      Next
    End With
  Selection.HomeKey wdStory
End If

Set RE = Nothing
Set REMatches = Nothing
Set mch = Nothing

End Sub

推荐阅读