5

This is basic stuff, but I'm somewhat unfamiliar with VBA and the Word/Access object models.

I have a two column database of about 117000 records. The columns are 'surname' and 'count'. I want a user to be able to type SMITH in a textbox and hit submit. I then want to run something like

SELECT table.count FROM table WHERE surname = string

and return the value of table.count in a string.

It feels like this should be five or six lines of code (which I have but won't post) but I'm obviously missing something!

Cheers

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

Table and columns actually have real names, and there are more columns, but I wanted to work that bit out for myself so I actually learn something. Thanks!
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.