将宏运行到特定样式

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

下面的代码试图将小写的单词转换为大写。但是,我只需要以特定的文字样式(“普通”)运行它。我试图将doc设置为ActiveDocument.Styles(“ Normal”),但我不断出错。任何帮助将是最有帮助的。先感谢您。

Option Explicit

   Public Sub TitleCaseDocument()
   Dim doc As Document: Set doc = ActiveDocument.Styles("Normal")
   Dim wrd As Range

   For Each wrd In doc.Words
       If wrd.Text <> UCase$(wrd.Text) Then wrd.Case = wdTitleWord
Next
End Sub
vba ms-word styles
2个回答
1
投票

@ eaazel提供的解决方案属于默认成员陷阱。

代码

wrd.Style

实际上使用的是样式对象的默认成员,即'NameLocal'。因此,上面的代码隐含的代码实际上是

wrd.Style.NameLocal

[通常这不是问题,但是,用于提取样式对象的粒度级别意味着,有时会遇到没有样式的单词(例如ToC字段)。在这种情况下,返回的样式对象为空,这会产生令人惊讶的错误,因为您无法在不为空的对象上调用NameLocal方法。

因此,更正确的方法是使用一个保证具有样式对象(例如段落)的单词单元,并在测试每个单词之前测试该对象上的样式。

Option Explicit

Public Sub TitleCaseDocument()
    Dim myDoc As Document: Set myDoc = ActiveDocument

    Dim myPara As Range
    For Each myPara In myDoc.StoryRanges.Item(wdMainTextStory).Paragraphs

        If myPara.Style.NameLocal = "Normal" Then

            TitleParagraph myPara

       End If

    Next

End Sub

Public Sub TitleParagraph(ByVal ipRange As Word.Range)

    Dim myText As Range
    For Each myText In ipRange.Words

        If Not UCase$(myText.Text) = myText.Text Then

            myText.Words.Item(1).Case = wdTitleWord

        End If

    Next

End Sub

更新2020-Apr-16修订的代码,下面的代码已被证明可用于Word文档。

选项显式

Public Sub TitleCaseDocument()
    Dim myDoc As Document: Set myDoc = ActiveDocument

    Dim myPara As Word.Paragraph
    For Each myPara In myDoc.StoryRanges.Item(wdMainTextStory).Paragraphs

        If myPara.Style.NameLocal = "Normal" Then

            TitleParagraph myPara

       End If

    Next

End Sub

Public Sub TitleParagraph(ByVal ipPara As Word.Paragraph)

    Dim myText As Range
    For Each myText In ipPara.Range.Words

        If Not UCase$(myText.Text) = myText.Text Then

            myText.Words.Item(1).Case = wdTitleWord

        End If

    Next

End Sub

1
投票

因此,如果样式正常,是否要将小写字母更改为大写字母?是?我没有丰富的单词经验,但也许这样的东西对您有所帮助(根据您的代码):

Public Sub TitleCaseDocument()
   Dim doc As Document: Set doc = ActiveDocument
   Dim wrd As Range

   For Each wrd In doc.Words

       If wrd.Text <> UCase$(wrd.Text) And wrd.Style = "Normal" Then
       wrd.Text = UCase$(wrd.Text)

       End If
Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.