从Excel中的Access表中检索值

时间:2014-08-19 11:19:17

标签: sql excel-vba vba excel

我有一个将数据导出到Word中的Excel文件。它包括一个封面页并抓取用户名(“First.Last”)并将其更改为“First Last”,但我还需要包含用户的专业标题。此信息位于Access表中。它有一个名为Name的字段和一个名为Title的字段。 “名称”字段与“用户”完全匹配,没有重复项。

我尝试了八种不同的方法,我在网上找到了从表中获取此值的方法。该表永远不会打开,所以我不能使用“CurrentDB()”。

我只需要能够进入数据库中的表,获取“title”值,因为字段“Name”的值等于User的值(来自环境的用户名 - 该人使用excel文件)。

如果有帮助,我可以举例说明目前我用过的不同代码块。

用户是环境中的用户名 tblPickName是我要打开的表 Path是表所在的目录和文件

tblPickName有2个字段,名称和标题 我需要从这个表中获取Title并将其设置为我的变量“Title”,只要Name等于User。然后我可以将用户名和标题导出到Word以及其余数据。

Dim Path As String
Dim User As String
Dim Title As String

Dim db As DAO.Database
Dim rs As DAO.Recordset

User = Environ("UserName")
User = Replace(User, ".", " ")
User = StrConv(User, vbProperCase)

Path = "Directory\Name.mdb"

Set db = DBEngine.OpenDatabase(Path)
Set rs = db.OpenRecordset("SELECT tblPickAnalyst.Title FROM tblPickAnalyst WHERE [Analyst]='" & User & "'")

Title = rs!Title

rs.Close
db.Close
Set rs = Nothing
Set db = Nothing

docWord.Bookmarks("AnalystName").Range.Text = User
docWord.Bookmarks("AnalystTitle").Range.Text = Title

3 个答案:

答案 0 :(得分:1)

试试这个:

Public Sub JohnTayloristheBest()
Dim conAccess As ADODB.Connection
    Set conAccess = New ADODB.Connection
Dim rdsAccess As ADODB.Recordset
Dim strTitle as String

With conAccess
    .ConnectionString = "Data Source= **insert filepath here** "
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open
End With

With rdsAccess
   .Open "SELECT tblPickName.Title FROM tblPickName WHERE tblPickName.Name = '" & Environ("username") & "';", conAccess
   If Not .EOF And Not IsNull(.fields(0)) Then
        strTitle = .fields(0)
   Else
        Msgbox "Error: No record in the database for " & Environ("username")
   End If
   .Close
End With

conAccess.Close: conAccess = Nothing
End Sub

请务必选择正确的引用:http://msdn.microsoft.com/en-us/library/windows/desktop/ms677497(v=vs.85).aspx

此外,这是我在本网站(或其他任何内容)上写的第一个答案,所以要善待。

答案 1 :(得分:0)

试试这个:

Public Function getTitle(name As String)

Dim db As DAO.Database
Dim rs As DAO.Recordset

  Set db = DBEngine.OpenDatabase("E:\Temp\Database.mdb")
  Set rs = db.OpenRecordset("SELECT Title FROM tblPickName WHERE Name='" & name & "'")
  If rs.RecordCount > 0 Then
    getTitle = rs!Title
  End If
  rs.Close
  db.Close

End Function

确保对表tblPickName(对于管理员)

的读访问权限

答案 2 :(得分:0)

这是最终的解决方案。感谢所有帮助过的人!

Dim Path As String
Dim User As String
Dim Title As String

Dim db As DAO.Database
Dim rs As DAO.Recordset

User = Environ("UserName")
User = Replace(User, ".", " ")
User = StrConv(User, vbProperCase)

Path = "Directory\FileName"

Set db = DBEngine.OpenDatabase(Path)
Set rs = db.OpenRecordset("SELECT tblPickAnalyst.Title FROM tblPickAnalyst WHERE [Analyst]='" & User & "'")

Title = rs!Title

rs.Close
db.Close
Set rs = Nothing
Set db = Nothing

docWord.Bookmarks("AnalystName").Range.Text = User
docWord.Bookmarks("AnalystTitle").Range.Text = Title