Word VBA脚本编译时不会出错,但不会';行不通

Word VBA脚本编译时不会出错,但不会';行不通,vba,ms-word,Vba,Ms Word,我在下面编写VBA宏是为了加强一些Word 2010样式的规范,这些规范在我的报告编写过程中往往会被拆散。宏编译时不会出错,但是当我在一个测试报告上运行宏时,除了样式名分配之外,所有的格式都被删除了,什么也没有发生 Sub ntsReportFormatting() Dim ntsReportDoc As Word.Document Dim ntsNormal As Style Dim ntsTOC1 As Style Dim ntsTOC2 As Style

我在下面编写VBA宏是为了加强一些Word 2010样式的规范,这些规范在我的报告编写过程中往往会被拆散。宏编译时不会出错,但是当我在一个测试报告上运行宏时,除了样式名分配之外,所有的格式都被删除了,什么也没有发生

Sub ntsReportFormatting()

    Dim ntsReportDoc As Word.Document

    Dim ntsNormal As Style
    Dim ntsTOC1 As Style
    Dim ntsTOC2 As Style
    Dim ntsTOC3 As Style

    Set ntsReportDoc = ActiveDocument

    Set ntsNormal = ntsReportDoc.Styles("Normal")
    With ntsNormal
        .Font.Name = "Arial"
        .Font.Size = 12
        .ParagraphFormat.LeftIndent = 0.5
        .ParagraphFormat.SpaceAfter = 0.6
    End With

    Set ntsTOC1 = ntsReportDoc.Styles("TOC 1")
    With ntsTOC1
        .Font.Name = "Arial"
        .Font.Size = 12
        .Font.Bold = True
        .ParagraphFormat.LeftIndent = 0
        .ParagraphFormat.SpaceBefore = 0.6
        .ParagraphFormat.SpaceAfter = 0.6
    End With

    Set ntsTOC2 = ntsReportDoc.Styles("TOC 2")
    With ntsTOC2
        .Font.Name = "Arial"
        .Font.Size = 12
        .ParagraphFormat.LeftIndent = 0.17
        .ParagraphFormat.SpaceBefore = 0.6
        .ParagraphFormat.SpaceAfter = 0.6
        .NoSpaceBetweenParagraphsOfSameStyle = True
    End With

    Set ntsTOC3 = ntsReportDoc.Styles("TOC 3")
    With ntsTOC3
        .Font.Name = "Arial"
        .Font.Size = 12
        .ParagraphFormat.LeftIndent = 0.33
        .ParagraphFormat.SpaceBefore = 0.6
        .ParagraphFormat.SpaceAfter = 0.6
        .NoSpaceBetweenParagraphsOfSameStyle = True
    End With

End Sub

我已经咨询了Lynda.com、MSDN文档、Youtube和Google,还没有找到明确的解决方案。

我无法确认问题,宏工作正常,根据定义的参数更改样式。

我遇到的问题是它更新了样式,但没有更新文档文本

我所做的是在重置
样式后运行
循环

在上次样式编辑语句之后添加此项

For p = 1 To ActiveDocument.Paragraphs.Count

    ActiveDocument.Paragraphs(p).Range.Select

    ParaStyle = ActiveDocument.Paragraphs(p).Range.style

    Selection.Range.style = ParaStyle

Next

我不确定是否有其他方法可以做到这一点。

这对我来说也很好,但根据Jean Pierre的回答,我想知道文本是否采用了直接格式。这将覆盖样式格式,因此不会显示对样式的更改

有一组命令可以从当前选择中删除各种类型的格式。它们都以“清晰”一词开头

例如,我选择了一个段落并应用了不同的字体。更改样式直到我第一次这样做时才出现:

ntsReportDoc.Select
Selection.ClearCharacterDirectFormatting

但是你必须意识到,如果没有使用样式应用斜体等等,这种方法也可以删除斜体。

这实际上非常有用!它为某人工作!也许我需要在某个地方选中或取消选中某个框…尝试用WDBuildinStyle枚举值替换文字字符串值-例如,wdStyleNormal而不是“Normal”-看看这是否有区别。您可以在VBA对象浏览器(F2)中找到该列表,如果键入WdBuiltinStyle,则Intellisense应提供该列表。(但请注意,我是从内存中提供的,所以我可能会打字!)可能是
样式确实更新了,但在文档文本中没有更新。它对我来说也很好,除了TOC样式,我没有在我的样式集中指定它们。