这是基本的东西,但我对VBA和Word / Access对象模型有些不熟悉。
我有一个大约117000条记录的两列数据库。列是'姓'和'计数'。我希望用户能够在文本框中键入SMITH并点击提交。然后我想运行像
这样的东西 SELECT table.count FROM table WHERE surname = string
并以字符串形式返回table.count的值。
感觉这应该是五行或六行代码(我有但不会发布)但我显然错过了一些东西!
干杯
答案 0 :(得分:6)
首先,要小心命名列'count' - 这是SQL中的关键字,可能会导致问题。同样,不要调用表'table'。
以下是一些示例代码,其中显示了一种方法:
' 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
答案 1 :(得分:4)
可以使用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
这是使用数据库工具栏记录的已编辑宏。
已编辑警告:此代码如图所示,受SQL注入攻击。