这是基本的东西,但我对VBA和Word/Access对象模型有点不熟悉.
我有一个大约117000条记录的两列数据库.列是'姓'和'计数'.我希望用户能够在文本框中键入SMITH并点击提交.然后我想运行类似的东西
SELECT table.count FROM table WHERE surname = string
并在字符串中返回table.count的值.
感觉这应该是五行或六行代码(我有但不会发布)但我显然错过了一些东西!
干杯
首先,要小心命名列'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