使用 Excel VBA 编写和格式化 Word 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22569182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing & formatting word document using excel VBA
提问by Kyo
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:
我正在尝试使用 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
All I want to do is center the "Text Line 1" text. I have googled and tried all sorts of solutions to no avail.
我想要做的就是将“文本行 1”文本居中。我用谷歌搜索并尝试了各种解决方案都无济于事。
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!
更新:排序 - 就像需要在 VBA 中选择 MS Word 对象库参考一样简单,然后居中工作正常!
回答by Jason Clement
You need to set the Alignmentproperty of the ParagraphFormat object of the Style.
您需要设置Style 的 ParagraphFormat 对象的Alignment属性。
wrdDoc.Styles("SHeading").ParagraphFormat.Alignment = wdAlignParagraphCenter
It must be one of the WdParagraphAlignmentenumerations.
它必须是WdParagraphAlignment枚举之一。