How to return the value in one field based on lookup value in another field

只愿长相守 提交于 2019-12-04 10:11:31

First of all, be careful naming the column 'count' -- this is a keyword in SQL and might cause problems. Similarly, don't call the table 'table'.

Here is some sample code which shows one way of doing it:

' This example uses Microsoft ActiveX Data Objects 2.8,
' which you have to check in Tools | References

' Create the connection. This connection may be reused for other queries.
' Use connectionstrings.com to get the syntax to connect to your database:
Dim conn As New ADODB.Connection
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\tmp\Database1.accdb"

Dim cmd As New ADODB.Command
Set cmd.ActiveConnection = conn

' Replace anything which might change in the following SQL string with ?

cmd.CommandText = "select ct from tbl where surname = ?"

' Create one parameter for every ?

Dim param As ADODB.Parameter
Set param = cmd.CreateParameter("surname", adBSTR, adParamInput, , TextBox1.Text)
cmd.Parameters.Append param

Dim rs As ADODB.Recordset
Set rs = cmd.Execute

MsgBox rs("ct")

rs.Close
conn.Close
Fionnuala

It is possible to use InsertDatabase:

Sub GetData()
    ActiveDocument.Bookmarks("InsertHere").Select

    Selection.Range.InsertDatabase Format:=0, Style:=0, LinkToSource:=False, _
        Connection:="TABLE Members", SQLStatement:= _
        "SELECT [Count] FROM [Members]" _
        & " WHERE Surname='" _
        & ActiveDocument.FormFields("Text1").Result & "'", _
        DataSource:="C:\docs\ltd.mdb", From:=-1, To:= _
        -1, IncludeFields:=True
End Sub

This is an edited macro recorded using the database toolbar.

EDITED Warning: this code, as shown, is subject to a SQL Injection attack.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!