从表中获取数据并将其放入模板中

时间:2015-12-07 12:02:09

标签: vba templates access-vba ms-access-2007 word-vba

我坐在一个单词模板上,我必须通过Access 2007生成模板。我有以下代码:

Public Function CH05_Generate()

Dim WordApp As Word.Application
Dim Doc As Word.Document
Dim WordPath As String
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim sql As String

Set db = CurrentDb()
Set rst = db.OpenRecordset("Projektdata", dbOpenDynaset)


WordPath = "Where my word template is"

Set WordApp = CreateObject("Word.Application")
Set Doc = WordApp.Documents.Add(WordPath)

With Doc

    .FormFields("PName").Result = [Projektnavn]
    .FormFields("text").Result = Forms![TD-E-PM200-CH05]!Kommentar
    .FormFields("S3").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q1
    .FormFields("S4").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q2
    .FormFields("S5").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q3
    .FormFields("S6").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q4
    .FormFields("S7").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q5
    .FormFields("S8").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q6
    .FormFields("S9").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q7
    .FormFields("S10").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q8
    .FormFields("S11").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q9
    .FormFields("S12").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q10
    .FormFields("S13").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q11
    .FormFields("S14").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q12
    .FormFields("S15").CheckBox.Value = Forms![TD-E-PM200-CH05]!sub.Form!Q13
    .FormFields("S16").CheckBox.Value = Forms![TD-E-PM200-CH05]!sub.Form!Q14
    .FormFields("S17").CheckBox.Value = Forms![TD-E-PM200-CH05]!sub.Form!Q15
    .FormFields("S18").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q16
    .FormFields("S19").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q17
    .FormFields("S20").Result = Forms![TD-E-PM200-CH05]!sub.Form!Q18        
End With

WordApp.visible = True
WordApp.Activate
WordApp.ActiveDocument.Protect wdAllowOnlyFormFields, True

End Function

我需要帮助的是从名为“Projektdata”的表中获取“Projektnavn”,但我不知道如何从中获取数据。有许多“projektnavn”,所以也许我应该做某种查找? 你可以看到他们都有一个sagsnr,也许这有帮助吗?

1 个答案:

答案 0 :(得分:0)

记录集rst的内容取决于查询Projektdata的设计方式。如果查询返回单行,则只需使用列名称即可检索数据:

If Not rst.EOF Then
    .FormFields("PName").Result = rst("YOUR_COLUMN_NAME")
End If

如果查询未返回任何行,则需要If语句。

修改

我不知道查询Projektdata是如何设计的。为了使它只返回正确的行,您必须修改它以接受参数来标识要返回的行。如果sagsnr的参数对于每一行都是唯一的,则可以传递该参数。我已经扩展了代码示例并添加了一些清理:

Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim qdf As DAO.QueryDef

Set db = CurrentDb()

Set qdf = db.QueryDefs("Projektdata")
qdf!plSagsnr = 1  'Add parameter value to only fetch data where sagsnr is 1
Set rst = qdf.OpenRecordset

If Not rst.EOF Then
    Debug.Print rst("Field1")
End If

rst.Close
qdf.Close
db.Close

Set rst = Nothing
Set qdf = Nothing
Set db = Nothing