【问题标题】:How to populate word/fill Word from multiple tables using Access VBA如何使用 Access VBA 从多个表中填充单词/填充单词
【发布时间】:2019-01-08 22:16:27
【问题描述】:

我是 Access 新手;我自定义了下面的代码。问题是它打印主键而不是所引用字段的名称。

例如,在一个语句中,我希望在 Word 中打印机构名称,但它从我的表中的一个特定的 rinstitute 中返回主键。

FormFields("txtNQFLevel").Result = Me.NQFLLEVEL我想要另一个表中的这个字段,但在同一个查询中返回字符串值,而不是其相反的主键值

FormFields("txtInstitute").Result = Me.Institute_Name我希望这个字段来自另一个表但在同一个查询中返回字符串值而不是其相反的主键值

Function BursaryContractYear2()
    Dim appWord As Word.Application
    Dim doc As Word.Document
    Dim Path As String

    On Error Resume Next
    Error.Clear

    Path = "C:\Users\Motlatsi Motlhamme\Desktop\FillWordAccess.docx "
    Set appWord = GetObject(, "Word.Application")
    If Err.Number <> 0 Then
        Set appWord = New Word.Application
        appWord.Visible = True
    End If

    Set doc = appWord.Documents.Open(Path, , True)
    With doc
        .FormFields("txtFirstName").Result = Me.FIRST_NAMES
        .FormFields("txtSurname").Result = Me.SURNAME
        .FormFields("txtNQFLevel").Result = Me.NQFLLEVEL
        .FormFields("txtInstitute").Result = Me.Institute_Name
        appWord.Visible = True
        appWord.Activate
    End With

    Set doc = Nothing
    Set appWord = Nothing

End Function

【问题讨论】:

  • 一般情况下最好不要使用On Error Resume Next...,尤其是在解决问题时。您是在告诉 VBA 忽略所有错误。
  • 您没有提供足够的信息。 Me. 是什么?是表格吗?

标签: vba ms-access ms-word office-interop


【解决方案1】:

在 Word 文档的 txtInstitute 字段中插入的数据是 Me.Institute_NameMe 指的是 VBA 代码运行的上下文,您的问题无法识别。但是,您在 Word 文档中获取主键这一事实表明,Institute_Name 是绑定到当前 Access 上下文的表中列的名称,其中包含指向 Institutes 表的外键。

在 Access 中,Institute_Field 列可能包含名称,而不是主键。 Access 将此称为lookup field。查找字段比传统的数据库概念foreign keys 更容易理解。但是,当您在查找字段的后台工作时,最终您需要了解 Access 一直对您隐藏的外键关系。

如果在Institutes 表的Name 列中找到您想要的名称,您可能可以通过将该行更改为:

.FormFields("txtInstitute").Result = DLookup("Name", "Institutes", "ID = " & Me.Institute_Name)

如果您需要多次执行此过程,您应该知道由于N+1 SELECT query issue 而效率低下。实现此结果的更有效方法是确保 Me 绑定到一个上下文,例如 joined table,其中包含您想要的数据。

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    相关资源
    最近更新 更多