使用excel VBA编写和格式化word文档



我想用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居中。我在谷歌上搜索并尝试了各种解决方案,但都无济于事。

有什么想法吗?

更新:排序它-这是简单的需要MS Word对象库参考选择在VBA,然后居中工作很好!

你需要设置Style的段落格式对象的对齐属性。

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

必须是WdParagraphAlignment枚举之一

最新更新