使用Excel VBA编写和格式化Word文档

4

我正在尝试使用Excel VBA编写Word文档。我可以创建一个Word文档,向其中写入文本,更改样式都没有问题。但是我想要居中一些文本,可我却无法弄清楚如何实现。以下是我用来编写文档的代码:

   Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = False

    Set wrdDoc = wrdApp.Documents.Add

    'Set up page settings
    With wrdApp.ActiveDocument.PageSetup
        .Orientation = wdOrientLandscape
        .TopMargin = wrdApp.InchesToPoints(0.98)
        .BottomMargin = wrdApp.InchesToPoints(0.98)
        .LeftMargin = wrdApp.InchesToPoints(0.98)
        .RightMargin = wrdApp.InchesToPoints(0.98)
    End With
    'End set up page settings

    With wrdDoc
        .Styles.Add ("SHeading")
        .Styles.Add ("StdText")

        With .Styles("SHeading").Font
            .Name = "Arial"
            .Size = 14
            .Bold = False
            .Underline = True
        End With
        With .Styles("StdText").Font
            .Name = "Arial"
            .Size = 8
            .Bold = False
            .Underline = False
        End With
    End With
    wrdApp.Selection.Collapse Direction:=wdCollapseEnd
    wrdApp.Selection.TypeParagraph
    wrdApp.Selection.Style = wrdDoc.Styles("SHeading")
    wrdApp.Selection.TypeText Text:="Text Line 1"


    wrdApp.Selection.TypeParagraph
    wrdApp.Selection.Style = wrdDoc.Styles("StdText")
    wrdApp.Selection.TypeText Text:="Text Line 2: "
    wrdApp.Selection.TypeParagraph

我想做的就是使“Text Line 1”文本居中。我已经谷歌并尝试了各种解决方案,但都无济于事。
有什么想法吗?
更新: 解决了——只需要在VBA中选择MS Word对象库引用,然后居中就可以正常工作了!

1
尝试在Word中将现有文本居中并录制宏,看看Word使用了什么。 - rheitzman
1个回答

1

您需要设置样式的ParagraphFormat对象的Alignment属性。

wrdDoc.Styles("SHeading").ParagraphFormat.Alignment = wdAlignParagraphCenter

它必须是WdParagraphAlignment枚举值之一。


我尝试了这个,但不幸的是它没有任何区别。它不会出现错误,只是无法使文本居中。我在样式分配或段落创建方面做错了什么吗? - Kyo
一旦我在VBA中为MS Word添加了引用,那么这个答案就非常好用。 - Kyo
我甚至没有考虑到常量在其他Office应用程序中不起作用。此外,文档也没有说明这些常量代表什么数字。有时候我会打开目标应用程序并使用MsgBox来查看这些常量的实际含义,例如:MsgBox wdAlignParagraphCenter。在这种情况下,wdAlignParagraphCenter表示1。因此,您也可以将对齐设置为1,而无需添加Word引用,它将执行您想要的操作。 - Jason Clement
2
这是另一个理由,要在现有模块的顶部添加 Option Explicit 并检查 IDE 的 Tools->Options 屏幕中的 Require Variable Declaration。如果您打开了此选项,您将看到哪些常量未被解析,而不是将其静默解释为零。 - pteranodon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接