vba - 使用 Document.Paragraphs.Add() 创建多个 Word 段落

标签 vba excel ms-word

我在 Excel 中使用宏向 Word 文档添加信息。我正在尝试将 10 行添加到现有的 Word 文档中,如下所示:

Sub AddParagraphs()

    'Open Word
    Dim wordApp As Word.Application
    Set wordApp = CreateObject("Word.Application")

    'Open
    Dim doc As Word.document
    Set doc = wordApp.Documents.Open("c:\temp\document.docx")

    'Add 10 paragraphs
    Dim idx As Integer
    For idx = 1 To 10

        Dim paragraph As Word.paragraph
        Set paragraph = doc.Paragraphs.Add()

        paragraph.Range.style = wdStyleHeading2
        paragraph.Range.text = "Paragraph " & CStr(idx)

    Next

    doc.Save

    doc.Close
    wordApp.Quit

End Sub

我在 C:\temp\document.docs 有一个空的 Word 文档,但运行代码后只有一行带有文本“第 10 段”。我期待10行。

据我所知,没有参数的 Paragraphs.Add() 应该创建一个新段落。也许我错误地认为一个新段落会产生一个新行?是否有另一种方法可以在循环中添加 10 行,其中每行都可以具有特定(不相同)的样式?

最佳答案

您添加的“段落”末尾没有段落标记。

将该行更改为

paragraph.Range.Text = "Paragraph " & CStr(idx) & vbCr

那应该可以解决您的问题。

关于vba - 使用 Document.Paragraphs.Add() 创建多个 Word 段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50121575/

相关文章:

vba - 根据类别从列表中随机选择一个项目,根据不同的数字重复次数

excel - 为细胞着色的另一种更快的方法

excel - "Unable to get the Countif property of the Worksheetfunction class"错误

mysql - 在不单击每个单元格的情况下更改标准格式的数字 - Excel

excel - MSEXCEL 将数据转置为数据库格式

vba - 如何让 Excel VBA 在 If and Then 之后停止

Android:从设备浏览并上传应用程序中的 PDF 或 Word 文件

c# - 如何使用 C#.NET 合并在 MS Word 中创建的表格的单元格?

vba - Microsoft Word 邮件合并数据源自动定位

vba - 将数据从 SQL Server 加载到 Excel 的最快方法