[英]Excel VBA - how to query Access database using column values as a parameter?
I have an Excel worksheet that has a list of about 1000 Item Numbers in column A on Sheet1. 我有一个Excel工作表,该工作表在Sheet1的A列中列出了大约1000个项目编号。 Currently, I import Sheet1 into an Access table named
ItemNumbers
and run the following query: 当前,我将Sheet1导入到名为
ItemNumbers
的Access表中,并运行以下查询:
SELECT MyTable.ItemNumber, MyTable.ItemName, MyTable.ItemPrice
FROM [ItemNumbers] INNER JOIN MyTable ON [ItemNumbers].ItemNumber = MyTable.ItemNumber
ORDER BY MyTable.ItemNumber;
And then I copy/paste the output to Sheet2. 然后,我将输出复制/粘贴到Sheet2。
How can I do this in VBA in Excel and put the results in a recordset? 如何在Excel中的VBA中执行此操作并将结果放入记录集中? I can figure out how to loop through the recordset and put the results in Sheet2.
我可以弄清楚如何遍历记录集并将结果放入Sheet2。 I'm just not sure on the code to run the query.
我只是不确定要运行查询的代码。
I have the following so far. 到目前为止,我有以下内容。 It just needs to be modified to use the values in Sheet1 Column A.
只需对其进行修改即可使用Sheet1列A中的值。
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\MyDatabase.accdb"
strSql = "SELECT MyTable.ItemNumber, MyTable.ItemName, MyTable.ItemPrice " & _
"FROM MyTable " & _
"WHERE WHERE (((MyTable.ItemNumber)= ??? IS IN Sheet1!A:A ??? )) " & _
"ORDER BY MyTable.ItemNumber;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
Thanks!!! 谢谢!!!
If I understand right; 如果我理解正确; what you ask is to
join
a table from Access with a table in Excel (ADODB). 你问什么是
join
从Access表与在Excel(ADODB)的表。
Check this link from SO, and see if it's helpful: 从SO上检查此链接,看看是否有帮助:
Selecting 2 tables from 2 different databases (ACCESS) 从2个不同的数据库中选择2个表(访问)
I haven't tried to combine Access and Excel before, but my guess is that it will work for Excel as well. 我之前没有尝试过将Access和Excel结合起来,但是我猜想它也将适用于Excel。
An alternate way (and that will certainly work): 另一种方法(肯定会起作用):
WHERE
clause and store the result in a recordset; WHERE
子句的查询,并将结果存储在记录集中; Exists
function if the ItemNumber from each record is available in the dictionary; Exists
函数检查字典中是否有每个记录的ItemNumber;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.