在具有多种字体的段落中应用格式

时间:2016-11-01 12:23:27

标签: vba ms-word word-vba

在我的文档中,我使用Arial或Courier New(代码),有时在同一段中。当我与其他人分享我的文档时,他们也倾向于使用其他字体,但重要的是保持对齐,这就是为什么我要创建一个宏,将所有非Courier New文本转换为Arial并进入正确的字体大小(11)。

到目前为止,我遇到了2个问题:

  1. 在混合字体的段落中,它倾向于将整个段落(包括代码)更改为Arial,而我只需要更改非代码文本
  2. 它不仅会改变正文中的字体大小,还会改变标题中的字体大小。
  3. 我认为我错误地使用了Word的对象(我在Excel中工作),但我无法在网上找到任何线索。有人可以帮帮我吗?

    Sub CorrectFont()
        Dim p As paragraph
        Set p = ActiveDocument.Paragraphs(1)
    
        Application.Visible = False
        Application.ScreenUpdating = False
    
        Do
            If p.Range.Font.Name <> "Courier New" Then
               p.Range.Font.Name = "Arial"
               p.Range.Font.Size = 11
            End If
            Set p = p.Next
        Loop Until p Is Nothing
    
        Application.ScreenUpdating = True
        Application.Visible = True
    End Sub
    

2 个答案:

答案 0 :(得分:1)

您可以检查每个单词,如下所示:

' Replaces non-Arial fonts with Arial.
' Exception: Courier New is not replaced.
Sub AlignFont()
    Dim wd As Range

    ' Check each word, one at a time.
    For Each wd In ActiveDocument.Words

        If Not (wd.Font.Name = "Arial" Or wd.Font.Name = "Courier New") Then

            wd.Font.Name = "Arial"
        End If
    Next
End Sub

答案 1 :(得分:0)

感谢@ destination-data的输入,我得到了代码的最终形式。我在这里介绍可能感兴趣的任何人。

再次感谢你!

Sub AlignFont()
Dim wd As Range

Application.Visible = False
Application.ScreenUpdating = False

' Check each word, one at a time.
For Each wd In ActiveDocument.Words

    'On objects like Contents it may create an error and crash
    On Error Resume Next
        If wd.Font.Name <> "Courier New" And wd.Style = "Normal" Then
            wd.Font.Name = "Arial"
        End If

        'To avoid any header that may have a "Normal" style
        If wd.Font.Bold = False Then
            wd.Font.Size = 11
        End If
Next

Application.ScreenUpdating = True
Application.Visible = True

End Sub