简体   繁体   中英

Writing & formatting word document using excel VBA

I'm trying to write a word document using excel VBA. I can create a word doc, write text to it, change styles not a problem. What I want to do is center some text, I cant for the life of me figure it out. Here is the code I'm using to write the doc:

   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

All I want to do is center the "Text Line 1" text. I have googled and tried all sorts of solutions to no avail.

Any ideas out there?

UPDATE: Sort it - it was as simple as needing the MS Word Object Library reference selected in VBA, then the centering works fine!

You need to set the Alignment property of the ParagraphFormat object of the Style.

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

It must be one of the WdParagraphAlignment enumerations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM