首页 > 解决方案 > 如何从 Excel 宏中创建 Word 段落格式对象

问题描述

我从 Excel 宏中创建了一个新的 Word 文档,并且效果很好。现在我想创建一个新的 ParagraphFormat 对象以应用于很多段落。Microsoft Office 开发中心提供了一个 word 中的宏示例。

Set oWord_app = CreateObject("Word.Application")
oWord_app.Documents.Add
Set oDoc = oWord_app.Documents(1)

'Micorsoft Def Center:
Dim myParaF As New ParagraphFormat 
myParaF.Alignment = wdAlignParagraphCenter 
myParaF.Borders.Enable = True 
ActiveDocument.Paragraphs(1).Format = myParaF

为了使这个 Word 宏适应我的 Excel 宏,我想我必须写

Dim myParaF as new oWord_app.ParagraphFormat

但那失败了。什么是正确的方法?

标签: excelvbaobjectms-word

解决方案


感谢您的意见。对不起,但我真的没想到要检查参考资料。我只引用了 Microsoft Office 14.0 对象库,现在我还引用了 Microsoft Word 14.0 对象库。现在它可以工作了。新语句显然是必要的,否则我会收到错误“变量未知”。我仍然想知道为什么它只有在没有“Word_app. ParagraphFormat”,但已经有了“ParagraphFormat”。非常感谢。

这是我的代码:

    Option Explicit
    Dim Word_app As Object, oDoc As Object, bWordVorhanden As Boolean, pFormat As Object

Sub DocumentCreate()

    Set Word_app = CreateObject("Word.Application")
    Word_app.Visible = True
    Word_app.Documents.Add
    Set oDoc = Word_app.Documents(1)

Set pFormat = New ParagraphFormat 
pFormat.Alignment = wdAlignParagraphCenter
pFormat.Borders.Enable = True
ActiveDocument.Paragraphs(1).Format = pFormat

    With oDoc.Paragraphs(1).Range
        .Font.Name = "Arial"
        .Font.Size = 11
        .Font.Bold = True
        .ParagraphFormat.Alignment = 1 'wdAlignParagraphCenter
        .InsertAfter "hello" 'Text:=Str(oDoc.Paragraphs.Count)
        .ParagraphFormat.SpaceBefore = 12
        .ParagraphFormat.SpaceAfter = 6
    End With

End Sub

推荐阅读