【问题标题】:Access to Word: student listing via VBA访问 Word:通过 VBA 的学生列表
【发布时间】:2016-03-10 00:27:04
【问题描述】:

我在 Microsoft Access 中有以下学生表:

name | email_address
--------------------
Student 1 | student1@example.com
Student 2 | student2@example.com
Student 3 | student3@example.com

我也有这样的 Microsoft Word 文档:

List of students

Name: __________________________________
Email address: ___________________________________

我想通过 VBA 代码完成一个新的 Microsoft Word 文档,使用以前的文档作为模板,因此输出如下:

List of students:

Name: Student 1
      _________
Email address: student1@example.com
               ____________________

Name: Student 2
      _________
Email address: student2@example.com
               ____________________

Name: Student 3
      _________
Email address: student3@example.com
               ____________________

这里需要注意的是,我不能假设这张桌子只能容纳 3 名学生,如上例所示;它可能有 4、5、6……甚至可能是十亿!

我想通过 VBA 代码实现这一点,但不知道如何实现。到目前为止,我唯一的代码是:

Private Sub btnOpenDocument_Click()
    OpenStudentListing
End Sub

Private Sub OpenStudentListing()
    Dim appword As Word.Application
    Dim doc As Word.Document

    On Error Resume Next
    Error.Clear
    Set appword = GetObject(, "word.application")
    If Err.Number <> 0 Then
        Set appword = New Word.Application
        appword.Visible = True
    End If

    filePath = ExtractTemplate(Student_Listing)
    If IsNull(filePath) Then Exit Sub
    Set doc = appword.Documents.Open(filePath)
    'The document opens just fine, but now what?
End Sub

这甚至有可能实现吗?如果有,怎么做?

【问题讨论】:

  • 为什么要使用VBA?使用 word 中的 mailmerge 功能,这将非常容易(google it)。

标签: vba ms-access ms-word


【解决方案1】:

将 docx 保存为 dotx(真正的 Word 模板,可以容纳您需要的其他内容)。

从要在文档中重复的文本(要插入数据的位置)创建一个 Building Block 条目,并将其保存在模板中。保存并关闭模板。

使用 Documents.Add 方法而不是 Documents.Open 以基于模板创建新文档。

循环您的记录并为每个记录插入构建基块。

(请注意,我的答案基于您提供的信息,这是有限的。它很可能缺少一些拼图,因为我不知道您做什么和不知道。互联网上有很多例子那种你可以找到更多细节的东西......)

【讨论】:

    【解决方案2】:

    为什么不把它做成报告,然后从报告中做出你想要的(Excel、Word、PDF ...)。而被隐藏的原因当然可以通过Macro或者VBA直接输出到word中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多