【问题标题】:Writing & formatting word document using excel VBA使用excel VBA编写和格式化word文档
【发布时间】:2014-04-29 10:27:16
【问题描述】:

我正在尝试使用 excel VBA 编写一个 word 文档。我可以创建一个 word 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

我想要做的就是将“Text Line 1”文本居中。 google了一下,各种办法都试过了,都没用。

有什么想法吗?

更新: 排序 - 就像需要在 VBA 中选择 MS Word 对象库引用一样简单,然后居中工作正常!

【问题讨论】:

  • 尝试在 Word 中居中现有文本的同时录制宏,看看 Word 使用什么。

标签: excel vba ms-word


【解决方案1】:

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

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

它必须是WdParagraphAlignment 枚举之一。

【讨论】:

  • 我试过这个,但不幸的是它没有任何区别。它不会引发错误,只是不会使文本居中。我在分配样式或段落创建方面做错了吗?
  • 一旦我在 vba 中为 ms word 添加了参考,那么这个答案就很好用。
  • 我什至没有考虑到常量在其他 Office 应用程序中不起作用。此外,文档没有指定常量代表什么数字。有时我发现自己打开目标应用程序并 MsgBoxing 常量只是为了查看它们的实际含义,例如:MsgBox wdAlignParagraphCenter。在这种情况下,wdAlignParagraphCenter 表示 1。因此,您也可以将 Alignment 设置为 1,它会按照您的意图进行操作,而无需添加 Word 引用。
  • 这是将Option Explicit 添加到现有模块顶部并在IDE 的工具-> 选项屏幕中选中需要变量声明的另一个原因。如果你打开了这个,你会看到哪些常量没有被解析,而不是默默地解释为零。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多