Vba 将数据从Access数据库拉入Word文档

Vba 将数据从Access数据库拉入Word文档,vba,automation,ms-access-2010,ms-word,Vba,Automation,Ms Access 2010,Ms Word,我正在尝试将Access数据库中的数据传输到Word文档中。我使用Excel执行了类似的过程,我需要使用Access而不是Excel对其进行编码 Excel代码(类似于此) 然后 在Access中,我无法通过在表中查找字符串并使用某种偏移过程在找到的字符串旁边查找字符串来提取数据。我不知道Access中的表结构是什么。。。所以我假设如下: 该表将命名为Table1。。。有两个字段Col1和Col2。。。您将搜索的一个值(示例“aword”)在Col1中,相应的结果将在Col2中 代码如下: Pu

我正在尝试将Access数据库中的数据传输到Word文档中。我使用Excel执行了类似的过程,我需要使用Access而不是Excel对其进行编码

Excel代码(类似于此)

然后


在Access中,我无法通过在表中查找字符串并使用某种偏移过程在找到的字符串旁边查找字符串来提取数据。我不知道Access中的表结构是什么。。。所以我假设如下:

该表将命名为Table1。。。有两个字段Col1和Col2。。。您将搜索的一个值(示例“aword”)在Col1中,相应的结果将在Col2中

代码如下:

Public Function GetAccess(strData As String)
   Dim db As DAO.Database
   Dim rst As DAO.Recordset
   Dim strDB As String
   Dim strSQL As String
   Dim strResult As String

   'Change Table1, Col1, Col2 to your liking correspondingly
   strSQL = "Select Col2 from Table1 where Col1 = """ & strData & """"
   strDB = "C:\\Users\\jn\\Documents\\Trial.accdb"  'Change it to your database name

   Set db = OpenDatabase(strDB)
   Set rst = db.OpenRecordset(strSQL)
   If rst.RecordCount > 0 Then
      strResult = rst.Fields("Col2") 'Remember to change Col2 to your own Column name
   Else
      strResult = ""
   End If
   rst.Close
   db.Close

   Set rst = Nothing
   Set db = Nothing

   GetAccess = strResult
End Function
因此,如果您想找到结果,下面是调用上述函数的代码:

Dim strResult As String

strResult = GetAccess("aword")

在Access上,必须查询具有列名的数据库/表才能查找数据,不能使用.Range().find()填充。。。
Public Function GetAccess(strData As String)
   Dim db As DAO.Database
   Dim rst As DAO.Recordset
   Dim strDB As String
   Dim strSQL As String
   Dim strResult As String

   'Change Table1, Col1, Col2 to your liking correspondingly
   strSQL = "Select Col2 from Table1 where Col1 = """ & strData & """"
   strDB = "C:\\Users\\jn\\Documents\\Trial.accdb"  'Change it to your database name

   Set db = OpenDatabase(strDB)
   Set rst = db.OpenRecordset(strSQL)
   If rst.RecordCount > 0 Then
      strResult = rst.Fields("Col2") 'Remember to change Col2 to your own Column name
   Else
      strResult = ""
   End If
   rst.Close
   db.Close

   Set rst = Nothing
   Set db = Nothing

   GetAccess = strResult
End Function
Dim strResult As String

strResult = GetAccess("aword")