简体   繁体   English

Excel VBA-如何使用列值作为参数查询Access数据库?

[英]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): 另一种方法(肯定会起作用):

  1. Run the query without the WHERE clause and store the result in a recordset; 运行不带WHERE子句的查询,并将结果存储在记录集中;
  2. Store the data from the Excel sheet that you require in a dictionary, where the ItemNumber (PK?) is the key; 将需要的Excel工作表中的数据存储在字典中,其中ItemNumber(PK?)为键;
  3. Run through the recordset, and check with the typical dictionary Exists function if the ItemNumber from each record is available in the dictionary; 运行记录集,并使用典型的字典Exists函数检查字典中是否有每个记录的ItemNumber;
  4. If the record is availabe, store the recordset values in a separate array (or dictionary) that you can use for further manipulation, (or perform direct actions if that's what you want to do). 如果有记录,则将记录集值存储在单独的数组(或字典)中,以用于进一步操作(或执行直接操作,如果您要这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM